import 'package:cutdex/shared/widgets/error_notification_host.dart'; import '../../shared/layout/composer_layout.dart'; import '../../shared/theme/composer_style.dart'; import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex_sdk/project.dart'; import '../../integrations/platform/platform_capabilities.dart'; import 'agent_composer_controller.dart'; import 'agent_composer_store.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../integrations/agent/agent_provider.dart'; import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../shared/widgets/drop_to_add_overlay.dart'; import '../settings/settings_page.dart'; import 'chat_controller.dart'; import 'chat_state.dart'; import '../../integrations/agent/conversation_repository.dart'; import '../../integrations/platform/native_project_drop_region.dart'; import '../../integrations/platform/native_file_drop_policy.dart'; import '../../workspace/media_import.dart'; import '../../workspace/external_media_import.dart'; import '../../settings/settings_operation.dart'; import '../../workspace/projects.dart'; import '../media/media_asset_drag.dart'; import '../media/media_browser_feedback.dart'; import 'agent_attachment_card.dart'; import 'agent_media_attachments.dart'; import 'agent_message_codec.dart'; import 'breakable_selectable_text.dart'; import 'composer_document.dart'; import 'composer_reference_validator.dart'; import 'composer_suggestion_surface.dart'; const _userTurnGap = 56.0; const _replyTurnGap = 48.0; String _elapsedLabel(BuildContext context, int elapsedMs) { final totalSeconds = ((elapsedMs + 999) ~/ 1000).clamp(1, 86400000); final minutes = totalSeconds ~/ 60; final seconds = totalSeconds % 60; final duration = minutes == 0 ? context.l10n.durationSeconds(totalSeconds) : context.l10n.durationMinutesSeconds(minutes, seconds); return context.l10n.agentElapsedTime(duration); } class AgentChatPanel extends ConsumerStatefulWidget { const AgentChatPanel({ super.key, this.projectId, this.timelineId, this.projectSelector, this.inputController, this.composer, this.conversationId, this.draftKey, this.onConversationCreated, this.onConversationUpdated, this.composerColor, }); final String? projectId; final String? timelineId; final Widget? projectSelector; final ComposerDocumentController? inputController; final AgentComposerController? composer; final String? conversationId; final String? draftKey; final Color? composerColor; final ValueChanged? onConversationCreated; final ValueChanged? onConversationUpdated; @override ConsumerState createState() => _AgentChatPanelState(); } class _AgentChatPanelState extends ConsumerState { late final ComposerDocumentController _input = widget.inputController ?? ComposerDocumentController(); final _scroll = ScrollController(); final _inputScroll = ScrollController(); final _footerKey = GlobalKey(); double _footerHeight = 0; bool _footerMeasureScheduled = false; bool _inputOverflows = false; bool _follow = true; String get _modelOperation => 'agent-model-${widget.projectId}-${widget.conversationId ?? widget.draftKey ?? 'new'}'; bool get _choosingModel => ref.read(settingsOperationProvider(_modelOperation)).isLoading; bool _usingDraftModel = false; bool _dropHovering = false; bool get _importingAttachments => _composer.busy || widget.projectId != null && ref.read(externalMediaImportProvider(widget.projectId!)).isLoading; late AgentComposerController _composer; List get _attachments => _composer.attachments; AgentComposerController _resolveComposer() => widget.composer ?? ref .read(agentComposerStoreProvider) .composer( widget.projectId, widget.conversationId ?? widget.draftKey ?? 'new', ); void _composerChanged() { if (mounted) setState(() {}); } void _scheduleFooterMeasure() { if (_footerMeasureScheduled) return; _footerMeasureScheduled = true; WidgetsBinding.instance.addPostFrameCallback((_) { _footerMeasureScheduled = false; if (!mounted) return; final height = _footerKey.currentContext?.size?.height ?? 0; if ((_footerHeight - height).abs() > 0.5) { setState(() => _footerHeight = height); if (_follow) { WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted && _scroll.hasClients) { _scroll.jumpTo(_scroll.position.maxScrollExtent); } }); } } }); } @override void didUpdateWidget(covariant AgentChatPanel oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.conversationId != widget.conversationId || oldWidget.projectId != widget.projectId || oldWidget.draftKey != widget.draftKey) { _usingDraftModel = false; _composer.removeListener(_composerChanged); _composer = _resolveComposer(); _composer.addListener(_composerChanged); } } String _errorMessage(BuildContext context, AgentChatError error) => switch (error) { AgentChatError.configurationReadFailed => context.l10n.agentConfigurationReadFailed, AgentChatError.configurationRequired => context.l10n.agentConfigurationRequired, AgentChatError.sessionRestoreFailed => context.l10n.agentSessionRestoreFailed, AgentChatError.contextBudget => context.l10n.agentContextBudgetExceeded, AgentChatError.authentication => context.l10n.agentAuthenticationFailed, AgentChatError.exportReplyFailed => context.l10n.agentExportReplyFailed, AgentChatError.connection => context.l10n.agentConnectionFailed, AgentChatError.protocol => context.l10n.agentProtocolFailed, AgentChatError.turnLimit => context.l10n.agentTurnLimitReached, AgentChatError.interrupted => context.l10n.agentTaskInterrupted, AgentChatError.recoveryRequired => context.l10n.agentRecoveryRequired, AgentChatError.replyFailed => context.l10n.replyFailed, AgentChatError.requestFailed => context.l10n.chatFailed, }; @override void initState() { super.initState(); _composer = _resolveComposer(); _composer.addListener(_composerChanged); _scroll.addListener(() { _follow = _scroll.position.extentAfter < 80; }); } @override void dispose() { _composer.removeListener(_composerChanged); if (widget.inputController == null) _input.dispose(); _scroll.dispose(); _inputScroll.dispose(); super.dispose(); } bool _canAttach(MediaAssetDrag drag) { final workspace = ref.read(projectsProvider).asData?.value; return widget.projectId == drag.projectId && workspace?.activeProject?.id == drag.projectId && !_attachments.any((item) => item.id == drag.assetId) && workspace!.assets.any((asset) => asset.id == drag.assetId); } bool _canAttachExternalFiles(List files) { if (files.isEmpty) return true; final assets = ref.read(projectsProvider).asData?.value.assets; if (assets == null) return false; final attachedIds = {for (final item in _attachments) item.id}; final attachedLocations = { for (final asset in assets) if (attachedIds.contains(asset.id)) ?mediaSourceLocation(asset), }; return files.any( (file) => !attachedLocations.contains(file.sourceUri.toString()), ); } void _attachAsset(AssetDocument asset) => _composer.attach(asset); bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop; Future _dropExternalFiles(List files) async { setState(() => _dropHovering = false); try { await _composer.importAttachments(files); } catch (_) { // Feedback belongs to the composer even if this panel is hidden. } } Future _pickAttachments() async { try { await _composer.pickAttachments(); } catch (_) { // Feedback belongs to the composer even if this panel is hidden. } } Widget _agentDropRegion(Widget child) { final workspace = ref.watch(projectsProvider).asData?.value; final enabled = _desktop && widget.projectId != null && workspace?.activeProject?.id == widget.projectId && (workspace?.projectBusy == false || _importingAttachments); final internal = DragTarget( key: const Key('agent-panel-drop-target'), hitTestBehavior: HitTestBehavior.opaque, onWillAcceptWithDetails: (details) => _canAttach(details.data), onAcceptWithDetails: (details) { final drag = details.data; if (!_canAttach(drag)) return; final asset = ref .read(projectsProvider) .asData! .value .assets .firstWhere((item) => item.id == drag.assetId); _attachAsset(asset); }, builder: (context, candidates, rejected) => Stack( fit: StackFit.expand, children: [ child, if (candidates.isNotEmpty || _dropHovering) const Positioned.fill( child: DropToAddOverlay(key: Key('agent-drop-overlay')), ), ], ), ); if (!_desktop) return internal; return NativeProjectDropRegion( regionId: 'attachments', policy: NativeFileDropPolicy.attachments, enabled: enabled, onEnter: (files) { if (!_importingAttachments && _canAttachExternalFiles(files)) { setState(() => _dropHovering = true); } }, onExit: () { if (mounted && _dropHovering) setState(() => _dropHovering = false); }, onDrop: _dropExternalFiles, child: internal, ); } @override Widget build(BuildContext context) { ref.watch(settingsOperationProvider(_modelOperation)); if (widget.projectId != null) { ref.watch(externalMediaImportProvider(widget.projectId!)); } final workspace = ref.watch(projectsProvider).asData?.value; final referenceValidator = ComposerReferenceValidator( workspace: workspace, projectId: widget.projectId, ); WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; referenceValidator.validate(_input); }); final provider = widget.projectId != null ? chatControllerProvider( widget.projectId!, conversationId: widget.conversationId, draftKey: widget.draftKey, ) : null; final state = provider == null ? const ChatState() : ref.watch(provider); final settings = ref.watch(agentSettingsProvider).asData?.value; final available = settings?.providers .where( (item) => item.enabled && AgentApiType.values.any( (type) => type.name == item.apiType, ) && item.models.isNotEmpty, ) .toList() ?? const []; final conversation = state.conversation; final showProjectSelector = widget.projectSelector != null && widget.conversationId == null && conversation == null && state.messages.isEmpty && !state.busy; final providerId = conversation?.providerId ?? settings?.selectedProviderId; final modelId = conversation?.modelId ?? settings?.selectedModelId; final selectedProvider = available .where((item) => item.id == providerId) .firstOrNull; final selectedModel = selectedProvider?.models .where((item) => item.id == modelId) .firstOrNull; final usingExisting = conversation != null || (widget.conversationId != null && !_usingDraftModel); final configured = usingExisting ? conversation != null && settings?.enabled == true && selectedModel != null : ref.watch(agentRuntimeProvider).asData?.value != null; Future chooseModel(String providerId, String modelId) async { if (_choosingModel || state.busy) return; final saved = await ref .read(settingsOperationProvider(_modelOperation).notifier) .run(() async { if (provider == null) { await ref .read(agentSettingsProvider.notifier) .selectModel(providerId, modelId); } else { await ref .read(provider.notifier) .selectModel(providerId, modelId); } }); if (!mounted || !context.mounted) return; if (saved) { setState(() => _usingDraftModel = true); } else { ErrorNotificationHost.of(context).show( ErrorNotification( content: Text(context.l10n.agentSaveSettingsFailed), ), ); } } final compactButtonStyle = AppComposerStyle.controlButton(context); final compactIconStyle = AppComposerStyle.controlIcon(context); Widget modelPicker() { if (available.isEmpty) { return TextButton.icon( key: const Key('agent-configure-model'), style: compactButtonStyle, onPressed: () => showSettingsPage(context, initialTab: 1), icon: const Icon(Icons.tune, size: 16), label: Text(context.l10n.agentConfigureModel), ); } return AppDropdownMenu( minWidth: 220, maxHeight: 320, items: [ if (usingExisting) AppMenuLabel(context.l10n.agentModelChangeSession), for (final item in available) ...[ AppMenuLabel(item.name), for (final model in item.models) AppMenuItem( label: model.id, selectOption: true, selected: item.id == providerId && model.id == modelId, onPressed: () => chooseModel(item.id, model.id), ), ], const Divider(height: 1), AppMenuItem( label: context.l10n.agentConfigureModel, selectOption: true, onPressed: () => showSettingsPage(context, initialTab: 1), ), ], builder: (context, toggle, focus) => AppToolbarDropdownButton( buttonKey: const Key('agent-model-picker'), focusNode: focus, onPressed: () { if (!state.busy && !_choosingModel) toggle?.call(); }, style: compactButtonStyle, child: Row( mainAxisSize: MainAxisSize.min, children: [ Flexible( child: Text( selectedModel?.id ?? context.l10n.agentSelectModel, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), const SizedBox(width: 4), const Icon(Icons.expand_more, size: 14), ], ), ), ); } if (provider != null) { ref.listen(provider, (previous, next) { if (_follow) { WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted && _scroll.hasClients) { _scroll.jumpTo(_scroll.position.maxScrollExtent); } }); } }); } void send() { referenceValidator.validate(_input); if (provider == null || widget.timelineId == null || !configured || _choosingModel || state.busy || _importingAttachments || _input.hasInvalidReferences || (_input.text.trim().isEmpty && _attachments.isEmpty)) { return; } final text = AgentComposerMessage.encodeDocument( _input.segments, _attachments, ); _input.clearDocument(); _composer.clear(); _follow = true; ref .read(provider.notifier) .send( text, timelineId: widget.timelineId!, onCreated: widget.onConversationCreated, onUpdated: widget.onConversationUpdated, ); } final theme = Theme.of(context); final content = _agentDropRegion( LayoutBuilder( builder: (context, constraints) { final panelWidth = (constraints.maxWidth - ComposerLayout.horizontalInset * 2) .clamp(0.0, ComposerLayout.maxWidth) .toDouble(); _scheduleFooterMeasure(); final footerInset = _footerHeight + ComposerLayout.bottomInset + AppSpacing.small; return Stack( children: [ Positioned.fill( child: Scrollbar( key: const Key('agent-conversation-scrollbar'), controller: _scroll, notificationPredicate: (notification) => notification.depth == 0 && notification.context ?.findAncestorWidgetOfExactType< ScrollEdgeFade >() != null, child: SizedBox( key: const Key('agent-conversation'), child: state.messages.isEmpty ? const SizedBox.expand() : ScrollEdgeFade( controller: _scroll, bottomInset: footerInset, child: ScrollConfiguration( behavior: const _NoAutomaticScrollbarBehavior(), child: ListView( controller: _scroll, padding: EdgeInsets.only(bottom: footerInset), children: [ Center( child: SizedBox( key: const Key( 'agent-conversation-content', ), width: panelWidth, child: Padding( padding: const EdgeInsets.symmetric( vertical: AppSpacing.compact, ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ for (final message in state.messages) Padding( padding: EdgeInsets.only( bottom: message.isUser ? _userTurnGap : _replyTurnGap, ), child: Column( crossAxisAlignment: message.isUser ? CrossAxisAlignment.end : CrossAxisAlignment .start, children: [ if (!message.isUser) ...[ if (message.elapsedMs case final elapsed?) Padding( padding: const EdgeInsets.only( bottom: AppSpacing .tiny, ), child: Row( mainAxisSize: MainAxisSize .min, children: [ Text( _elapsedLabel( context, elapsed, ), style: AppTheme.chatMetaTextStyle( context, ), ), Icon( Icons .chevron_right, size: 14, color: AppTheme.chatMetaTextStyle( context, ).color, ), ], ), ), Divider( height: 1, thickness: 1, color: theme.dividerColor, ), const SizedBox( height: AppSpacing.medium, ), ], if (AgentComposerMessage.decode( message.text, ).text.isNotEmpty) if (message.isUser) Container( decoration: AppTheme.userMessageDecoration( context, ), padding: const EdgeInsets.symmetric( horizontal: AppSpacing .medium, vertical: AppSpacing .itemVertical, ), child: BreakableSelectableText( text: AgentComposerMessage.decode( message.text, ).text, style: AppTheme.chatMessageTextStyle( context, ), ), ) else SelectableText( message.text, style: AppTheme.chatMessageTextStyle( context, ), ), if (message.isUser && AgentComposerMessage.decode( message.text, ) .attachments .isNotEmpty) Padding( padding: const EdgeInsets.only( top: 8, ), child: Wrap( spacing: 8, runSpacing: 8, alignment: WrapAlignment.end, children: [ for (final attachment in AgentComposerMessage.decode( message.text, ).attachments) if (ref .watch( projectsProvider, ) .asData ?.value .assets .where( ( asset, ) => asset.id == attachment.id, ) .firstOrNull case final asset?) AgentAttachmentCard( asset: asset, ) else Chip( label: Text( attachment .name, ), ), ], ), ), if (message.interrupted) Text( context .l10n .replyInterrupted, style: theme .textTheme .bodySmall, ), ], ), ), if (state.busy) ...[ if (state .partialResponse .isNotEmpty) SelectableText( state.partialResponse, style: AppTheme.chatMessageTextStyle( context, ), ), Text( state.stopping ? context.l10n.stopping : switch (state.activity) { AgentChatActivity .compacting => context .l10n .agentCompacting, AgentChatActivity .editing => context .l10n .agentEditing, AgentChatActivity .verifying => context .l10n .agentVerifying, AgentChatActivity .replying => context.l10n.replying, }, style: theme.textTheme.bodySmall, ), ], ], ), ), ), ), ], ), ), ), ), ), ), Positioned( left: ComposerLayout.horizontalInset, right: ComposerLayout.horizontalInset, bottom: ComposerLayout.bottomInset, child: NotificationListener( onNotification: (_) { _scheduleFooterMeasure(); return false; }, child: SizeChangedLayoutNotifier( key: _footerKey, child: Column( mainAxisSize: MainAxisSize.min, children: [ if (state.error case final error?) Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.compact, ), child: Text( _errorMessage(context, error), style: theme.textTheme.bodySmall, ), ), if ({ AgentChatError.recoveryRequired, AgentChatError.interrupted, AgentChatError.turnLimit, }.contains(state.error)) TextButton( onPressed: state.busy || widget.timelineId == null ? null : () => ref .read(provider!.notifier) .send( context.l10n.agentResumeTask, timelineId: widget.timelineId!, resumeOnly: true, onUpdated: widget.onConversationUpdated, ), child: Text(context.l10n.agentResumeTask), ), if (state.error == AgentChatError.exportReplyFailed) TextButton( onPressed: state.busy || widget.timelineId == null ? null : () => ref .read(provider!.notifier) .send( context.l10n.agentRetrySummary, timelineId: widget.timelineId!, summaryOnly: true, onUpdated: widget.onConversationUpdated, ), child: Text(context.l10n.agentRetrySummary), ), if (usingExisting && !configured && conversation != null) Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.compact, ), child: Text( context.l10n.agentModelUnavailable, style: theme.textTheme.bodySmall, ), ), Align( alignment: Alignment.bottomCenter, child: SizedBox( width: panelWidth, child: Stack( children: [ if (showProjectSelector) Positioned( top: ComposerLayout.utilityTopGap, left: ComposerLayout.utilityInset, right: ComposerLayout.utilityInset, child: widget.projectSelector!, ), Padding( padding: EdgeInsets.only( top: !showProjectSelector ? AppSpacing.small : ComposerLayout.composerTopWithUtility, ), child: Align( alignment: Alignment.bottomCenter, child: SizedBox( width: panelWidth, child: ComposerSuggestionSurface( controller: _input, width: panelWidth, projectId: workspace?.activeProject?.id, assets: workspace?.assets ?? const [], timelines: workspace?.timelines ?? const [], onSend: send, builder: (context, inputFocus) => Card( key: const Key('agent-composer'), color: widget.composerColor ?? AppSurfaces.of(context) .composerBackground, margin: EdgeInsets.zero, elevation: 0, surfaceTintColor: Colors.transparent, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( ComposerLayout.radius, ), ), child: Column( mainAxisSize: MainAxisSize.min, children: [ if (_attachments.isNotEmpty) SizedBox( height: 138, child: ListView.separated( key: const Key( 'agent-composer-attachments', ), scrollDirection: Axis.horizontal, padding: const EdgeInsets.fromLTRB( 12, 12, 12, 4, ), itemCount: _attachments.length, separatorBuilder: (_, _) => const SizedBox( width: 8, ), itemBuilder: (context, index) { final attachment = _attachments[index]; final asset = ref .watch( projectsProvider, ) .asData ?.value .assets .where( (item) => item.id == attachment.id, ) .firstOrNull; if (asset == null) { return const SizedBox.shrink(); } return AgentAttachmentCard( key: Key( 'agent-attachment-${asset.id}', ), asset: asset, onRemove: () => _composer.remove( asset.id, ), ); }, ), ), ConstrainedBox( // Leave room for messages and composer actions when this // panel shares a short window with the timeline. constraints: BoxConstraints( maxHeight: (constraints.maxHeight * ComposerLayout .inputMaxHeightFraction) .clamp( ComposerLayout .inputMinHeight, double.infinity, ), ), child: NotificationListener( onNotification: (_) { WidgetsBinding.instance .addPostFrameCallback(( _, ) { if (!mounted || !_inputScroll .hasClients) { return; } final overflows = _inputScroll .position .maxScrollExtent > 0; if (overflows != _inputOverflows) { setState( () => _inputOverflows = overflows, ); } }); return false; }, child: Scrollbar( key: const Key( 'agent-input-scrollbar', ), controller: _inputScroll, thumbVisibility: _inputOverflows, child: ScrollConfiguration( behavior: const _NoAutomaticScrollbarBehavior(), child: TextField( controller: _input, focusNode: inputFocus, scrollController: _inputScroll, style: AppTheme.composerTextStyle( context, ), cursorHeight: AppTheme.composerCursorHeight( context, ), textAlignVertical: TextAlignVertical .top, minLines: 1, maxLines: 12, keyboardType: TextInputType .multiline, textInputAction: TextInputAction .newline, decoration: AppComposerStyle.inputDecoration( context, hintText: context .l10n .assistantHint, ), ), ), ), ), ), ValueListenableBuilder< TextEditingValue >( valueListenable: _input, builder: (context, _, _) => _input.hasInvalidReferences ? Padding( padding: const EdgeInsets.symmetric( horizontal: 14, vertical: 4, ), child: Align( alignment: Alignment .centerLeft, child: Text( context .l10n .composerReferenceInvalid, style: theme .textTheme .bodySmall ?.copyWith( color: theme .colorScheme .error, ), ), ), ) : const SizedBox.shrink(), ), Padding( padding: AppComposerStyle .controlsPadding, child: Row( children: [ IconButton( style: compactIconStyle, tooltip: context .l10n .addAttachment, onPressed: widget.projectId != null && !_importingAttachments && ref .watch( platformCapabilitiesProvider, ) .localFileSelection ? _pickAttachments : null, icon: const Icon( Icons.add, ), ), const SizedBox( width: ComposerLayout .controlGap, ), Expanded( child: Align( alignment: AlignmentDirectional .centerStart, child: modelPicker(), ), ), const SizedBox( width: ComposerLayout .controlGap, ), if (state.busy) IconButton.filled( style: AppTheme.primaryIconButtonStyle( context, ).merge( compactIconStyle, ), tooltip: context .l10n .stopReply, onPressed: state.stopping ? null : ref .read( provider! .notifier, ) .stop, icon: const Icon( Icons.stop, ), ) else ValueListenableBuilder< TextEditingValue >( valueListenable: _input, builder: (context, value, child) => IconButton.filled( style: AppComposerStyle.composerSendButtonStyle( context, ).merge( compactIconStyle, ), tooltip: context .l10n .sendMessage, onPressed: provider != null && widget.timelineId != null && configured && !_importingAttachments && !_input .hasInvalidReferences && (value.text .trim() .isNotEmpty || _attachments .isNotEmpty) ? send : null, icon: const Icon( Icons.arrow_upward, ), ), ), ], ), ), ], ), ), ), ), ), ), ], ), ), ), ], ), ), ), ), ], ); }, ), ); return MediaImportFeedbackListener( feedback: _composer.feedback, child: content, ); } } /// Explicit scrollbars own their track instead of the desktop default wrapper. class _NoAutomaticScrollbarBehavior extends MaterialScrollBehavior { const _NoAutomaticScrollbarBehavior(); @override Widget buildScrollbar( BuildContext context, Widget child, ScrollableDetails details, ) => child; }