import 'agent_reply_region.dart'; import '../../workspace/projects.dart'; import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:cutdex_ui/icons.dart'; import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../shared/layout/composer_layout.dart'; import '../../shared/theme/composer_style.dart'; import '../../shared/widgets/workspace_resize_handle.dart'; import '../../l10n/l10n.dart'; import '../../workspace/project_state.dart'; import '../../workspace/external_media_import.dart'; import '../../integrations/agent/agent_provider.dart'; import '../../integrations/agent/conversation_repository.dart'; import '../projects/conversation_sidebar.dart'; import '../media/media_browser_feedback.dart'; import '../settings/settings_page.dart'; import '../../settings/settings_operation.dart'; import '../../shared/widgets/error_notification_host.dart'; import 'agent_chat_actions.dart'; import 'agent_attachment_card.dart'; import 'agent_attachment_drop_region.dart'; import 'agent_composer_controller.dart'; import 'agent_message_codec.dart'; import 'breakable_selectable_text.dart'; import 'chat_controller.dart'; import 'chat_state.dart'; import 'composer_document.dart'; import 'composer_reference_validator.dart'; import 'composer_suggestion_surface.dart'; /// Independent floating presentation of the same conversation and draft stores. class FloatingAgentPanel extends ConsumerStatefulWidget { const FloatingAgentPanel({ super.key, required this.state, required this.selection, required this.input, required this.composer, required this.expanded, required this.onToggleExpanded, required this.onDock, required this.onConversationCreated, required this.onConversationUpdated, }); final ProjectState state; final ConversationSelectionState selection; final ComposerDocumentController input; final AgentComposerController composer; final bool expanded; final VoidCallback onToggleExpanded; final VoidCallback onDock; final ValueChanged onConversationCreated; final ValueChanged onConversationUpdated; @override ConsumerState createState() => _FloatingAgentPanelState(); } class _FloatingAgentPanelState extends ConsumerState with SingleTickerProviderStateMixin { final _scroll = ScrollController(); late final AnimationController _reveal; bool _resizing = false; void _animateReveal(bool expanded) { _reveal.animateTo(expanded ? 1 : 0, curve: Curves.easeOutCubic); } void _startResize() { _reveal.stop(); setState(() => _resizing = true); } void _finishResize() { if (!_resizing) return; final expanded = _reveal.value >= .35; setState(() => _resizing = false); if (expanded != widget.expanded) { widget.onToggleExpanded(); } else { _animateReveal(expanded); } } void _changed() { if (mounted) setState(() {}); } @override void initState() { super.initState(); _reveal = AnimationController( vsync: this, duration: const Duration(milliseconds: 220), value: widget.expanded ? 1 : 0, ); widget.composer.addListener(_changed); } @override void didUpdateWidget(FloatingAgentPanel oldWidget) { super.didUpdateWidget(oldWidget); if (widget.expanded != oldWidget.expanded) { _animateReveal(widget.expanded); } if (oldWidget.input != widget.input) { WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted && _scroll.hasClients) { _scroll.jumpTo(_scroll.position.maxScrollExtent); } }); } if (oldWidget.composer != widget.composer) { oldWidget.composer.removeListener(_changed); widget.composer.addListener(_changed); } } @override void dispose() { widget.composer.removeListener(_changed); _reveal.dispose(); _scroll.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final assets = ref.watch( projectsProvider.select( (value) => value.asData?.value.activeProject?.id == widget.state.activeProject?.id ? value.asData?.value.assets : null, ), ) ?? widget.state.assets; final workspace = widget.state.copyWith(assets: assets); final projectId = workspace.activeProject?.id; final timelineId = widget.state.timeline?.id; final selection = widget.selection; final provider = projectId == null ? null : chatControllerProvider( projectId, conversationId: selection.selectedId, draftKey: selection.selectedId == null ? selection.draftKey : null, ); final chat = provider == null ? const ChatState() : ref.watch(provider.select(chatChrome)); final settings = ref.watch(agentSettingsProvider).value; final available = settings?.providers .where( (p) => p.enabled && AgentApiType.values.any((type) => type.name == p.apiType) && p.models.isNotEmpty, ) .toList() ?? []; final conversation = chat.conversation; final providerId = conversation?.providerId ?? settings?.selectedProviderId; final modelId = conversation?.modelId ?? settings?.selectedModelId; final selectedProvider = available .where((p) => p.id == providerId) .firstOrNull; final selectedModel = selectedProvider?.models .where((m) => m.id == modelId) .firstOrNull; final configured = conversation != null || (selection.selectedId != null && !widget.composer.usingDraftModel) ? conversation != null && settings?.enabled == true && selectedModel != null : ref.watch(agentRuntimeProvider).value != null; final importing = widget.composer.busy || (projectId != null && ref.watch( externalMediaImportProvider(projectId) .select((value) => value.isLoading), )); final operation = 'agent-model-$projectId-${selection.selectedId ?? selection.draftKey}'; final choosingModel = ref.watch( settingsOperationProvider(operation).select((value) => value.isLoading), ); final validator = ComposerReferenceValidator( workspace: workspace, projectId: projectId, ); WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) validator.validate(widget.input); }); if (provider != null && TickerMode.valuesOf(context).enabled) { ref.listen(provider, (old, next) { if (_scroll.hasClients && _scroll.position.extentAfter < 80) { WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted && _scroll.hasClients) { _scroll.jumpTo(_scroll.position.maxScrollExtent); } }); } }); } void send() { validator.validate(widget.input); if (provider == null || timelineId == null || !configured || choosingModel || chat.busy || importing || widget.input.hasInvalidReferences || (widget.input.text.trim().isEmpty && widget.composer.attachments.isEmpty)) { return; } final text = takeAgentDraft(widget.input, widget.composer); if (!widget.expanded) widget.onToggleExpanded(); unawaited( ref .read(provider.notifier) .send( text, timelineId: timelineId, onCreated: widget.onConversationCreated, onUpdated: widget.onConversationUpdated, ), ); } Future chooseModel(String p, String m) async { if (chat.busy || choosingModel) return; final composer = widget.composer; final saved = await ref .read(settingsOperationProvider(operation).notifier) .run(() async { if (provider == null) { await ref.read(agentSettingsProvider.notifier).selectModel(p, m); } else { await ref.read(provider.notifier).selectModel(p, m); } }); if (!mounted || !context.mounted) return; if (saved) composer.useDraftModel(); if (!saved && context.mounted) { ErrorNotificationHost.of(context).show( ErrorNotification( content: Text(context.l10n.agentSaveSettingsFailed), ), ); } } final groups = ref.watch(conversationSidebarProvider).value?.groups; final items = groups?[projectId] ?? const []; final title = conversation?.title ?? items.where((c) => c.id == selection.selectedId).firstOrNull?.title ?? context.l10n.agentNewConversation; final inputDecoration = AppComposerStyle.inputDecoration( context, hintText: context.l10n.assistantHint, ); Widget modelButton() => AppDropdownMenu( enabled: !chat.busy && !choosingModel, minWidth: ComposerLayout.menuWidth, maxHeight: ComposerLayout.menuListMaxHeight, items: [ for (final p in available) ...[ AppMenuLabel(p.name), for (final m in p.models) AppMenuItem( label: m.id, selectOption: true, selected: p.id == providerId && m.id == modelId, onPressed: () => unawaited(chooseModel(p.id, m.id)), ), ], const Divider(height: 1), AppMenuItem( label: context.l10n.agentConfigureModel, onPressed: () => showSettingsPage(context, initialTab: 1), ), ], builder: (context, toggle, focus) => Tooltip( message: selectedModel?.id ?? context.l10n.agentConfigureModel, child: AppToolbarDropdownButton( buttonKey: const Key('floating-agent-model-picker'), focusNode: focus, onPressed: toggle, style: AppComposerStyle.controlButton(context), child: const Icon(AppIcons.model, size: ComposerLayout.iconSize), ), ), ); final conversationView = ExcludeFocus( excluding: !widget.expanded && !_resizing, child: IgnorePointer( ignoring: !widget.expanded && !_resizing, child: LayoutBuilder( builder: (context, constraints) { final height = constraints.maxHeight.clamp( AppControlSize.panelToolbar + 1, double.infinity, ); return ClipRect( child: OverflowBox( alignment: Alignment.topCenter, minHeight: height, maxHeight: height, child: Column( children: [ SizedBox( height: AppControlSize.panelToolbar, child: Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.small, ), child: Row( children: [ IconButton( key: const Key('floating-agent-collapse'), style: AppComposerStyle.controlIcon(context), tooltip: context.l10n.agentCollapseConversation, onPressed: widget.onToggleExpanded, icon: const Icon( AppIcons.remove, size: AppIconSize.header, ), ), Expanded( child: AppDropdownMenu( minWidth: ComposerLayout.menuWidth, maxHeight: ComposerLayout.menuListMaxHeight, items: [ AppMenuItem( label: context.l10n.agentNewConversation, onPressed: () => ref .read( conversationSidebarProvider.notifier, ) .newConversation(), ), for (final item in items) AppMenuItem( label: item.title, selectOption: true, selected: item.id == selection.selectedId, onPressed: () { final controller = ref.read( conversationSidebarProvider.notifier, ); controller.activate(item); unawaited( controller.rememberSelection(item), ); }, ), ], builder: (context, toggle, focus) => AppToolbarDropdownButton( focusNode: focus, onPressed: toggle, child: Row( children: [ Flexible( child: Text( title, key: const Key( 'agent-floating-title', ), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), const SizedBox( width: AppSpacing.tiny, ), const Icon( AppIcons.expandMore, size: AppIconSize.header, ), ], ), ), ), ), IconButton( key: const Key('floating-agent-dock'), style: AppComposerStyle.controlIcon(context), tooltip: context.l10n.agentDock, onPressed: widget.onDock, icon: const Icon( AppIcons.exitFullscreen, size: AppIconSize.header, ), ), ], ), ), ), Expanded( child: ListView( controller: _scroll, key: const Key('floating-agent-messages'), padding: const EdgeInsets.all(AppSpacing.medium), children: [ for (final message in chat.messages) Padding( padding: const EdgeInsets.only( bottom: AppSpacing.large, ), child: Align( alignment: message.isUser ? Alignment.centerRight : Alignment.centerLeft, child: Container( constraints: const BoxConstraints( maxWidth: ComposerLayout.maxWidth, ), padding: message.isUser ? const EdgeInsets.symmetric( horizontal: AppSpacing.medium, vertical: AppSpacing.itemVertical, ) : EdgeInsets.zero, decoration: message.isUser ? AppTheme.userMessageDecoration(context) : null, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ if (message.elapsedMs case final elapsed?) Text( context.l10n.agentElapsedTime( context.l10n.durationSeconds( (elapsed / 1000).ceil(), ), ), style: AppTheme.chatMetaTextStyle( context, ), ), if (message.isUser) BreakableSelectableText( text: AgentComposerMessage.decode( message.text, ).text, style: AppTheme.chatMessageTextStyle( context, ), ) else SelectableText( AgentComposerMessage.decode( message.text, ).text, style: AppTheme.chatMessageTextStyle( context, ), ), for (final attachment in AgentComposerMessage.decode( message.text, ).attachments) Chip(label: Text(attachment.name)), if (message.interrupted) Text(context.l10n.replyInterrupted), ], ), ), ), ), AgentReplyRegion( projectId: projectId, conversationId: selection.selectedId, draftKey: selection.selectedId == null ? selection.draftKey : null, ), ], ), ), ], ), ), ); }, ), ), ); final composerView = Padding( key: const Key('floating-agent-input-area'), padding: const EdgeInsets.all(AppSpacing.small), child: LayoutBuilder( builder: (context, constraints) => ComposerSuggestionSurface( controller: widget.input, width: constraints.maxWidth, projectId: projectId, assets: assets, timelines: widget.state.timelines, onSend: send, builder: (context, focus) { final attachment = IconButton( style: AppComposerStyle.controlIcon(context), tooltip: context.l10n.addAttachment, onPressed: projectId == null || importing || widget.state.projectBusy ? null : () async { try { await widget.composer.pickAttachments(); } catch (_) { /* Shared composer publishes import feedback. */ } }, icon: const Icon(AppIcons.add), ); final input = TextField( key: const Key('floating-agent-input'), controller: widget.input, focusNode: focus, minLines: 1, maxLines: 5, style: AppTheme.composerTextStyle(context), cursorHeight: AppTheme.composerCursorHeight(context), decoration: inputDecoration.copyWith( constraints: const BoxConstraints( minHeight: ComposerLayout.controlSize, ), contentPadding: const EdgeInsets.symmetric( horizontal: AppSpacing.small, vertical: AppSpacing.tiny, ), ), onTap: () { if (!widget.expanded) { widget.onToggleExpanded(); } }, ); final submit = ValueListenableBuilder( valueListenable: widget.input, builder: (context, value, _) => IconButton.filled( style: AppTheme.accentIconButtonStyle(context) .merge(AppComposerStyle.controlIcon(context)), tooltip: chat.busy ? context.l10n.stopReply : context.l10n.sendMessage, onPressed: chat.busy ? (chat.stopping ? null : ref.read(provider!.notifier).stop) : provider != null && timelineId != null && configured && !importing && !choosingModel && !widget.input.hasInvalidReferences && (value.text.trim().isNotEmpty || widget.composer.attachments.isNotEmpty) ? send : null, icon: Icon( chat.busy ? AppIcons.squareFilled : AppIcons.arrowUp, size: chat.busy ? 12 : ComposerLayout.iconSize, ), ), ); // Keep the editor at the same tree position and bottom // anchor while the conversation opens above it. return Row( key: const Key('floating-agent-composer'), crossAxisAlignment: CrossAxisAlignment.end, children: [ attachment, Expanded(child: input), modelButton(), submit, ], ); }, ), ), ); final content = LayoutBuilder( builder: (context, constraints) { final conversationHeight = (constraints.maxHeight - ComposerLayout.controlSize - AppSpacing.small * 2) .clamp(0.0, double.infinity); return AnimatedBuilder( animation: _reveal, builder: (context, _) => MediaImportFeedbackListener( feedback: widget.composer.feedback, child: Material( color: Theme.of(context).colorScheme.surface, child: Stack( children: [ Column( mainAxisSize: MainAxisSize.min, children: [ Flexible( child: SizedBox( key: const Key('floating-agent-conversation-region'), height: conversationHeight * _reveal.value, child: ClipRect( child: Stack( children: [ Offstage( offstage: _reveal.value == 0, child: conversationView, ), Positioned( left: 0, right: 0, bottom: 0, child: Divider( key: const Key( 'floating-agent-input-divider', ), height: 1, thickness: 1, color: AppTheme.floatingDialogDividerColor( context, ), ), ), ], ), ), ), ), if (chat.error case final error?) Padding( padding: const EdgeInsets.all(AppSpacing.small), child: Text( agentChatErrorMessage(context, error), style: Theme.of(context).textTheme.bodySmall, ), ), if ({ AgentChatError.recoveryRequired, AgentChatError.interrupted, AgentChatError.turnLimit, AgentChatError.exportReplyFailed, }.contains(chat.error)) TextButton( onPressed: provider == null || timelineId == null || chat.busy ? null : () => ref .read(provider.notifier) .send( chat.error == AgentChatError.exportReplyFailed ? context.l10n.agentRetrySummary : context.l10n.agentResumeTask, timelineId: timelineId, summaryOnly: chat.error == AgentChatError.exportReplyFailed, resumeOnly: chat.error != AgentChatError.exportReplyFailed, onUpdated: widget.onConversationUpdated, ), child: Text( chat.error == AgentChatError.exportReplyFailed ? context.l10n.agentRetrySummary : context.l10n.agentResumeTask, ), ), ValueListenableBuilder( valueListenable: widget.input, builder: (context, _, _) => widget.input.hasInvalidReferences ? Padding( padding: const EdgeInsets.all(AppSpacing.small), child: Text( context.l10n.composerReferenceInvalid, style: AppSurfaces.of(context).errorText, ), ) : const SizedBox.shrink(), ), if (widget.composer.attachments.isNotEmpty) Padding( padding: const EdgeInsets.all(AppSpacing.small), child: Wrap( spacing: AppSpacing.gap, children: [ for (final asset in widget.composer.attachments) if (assets .where((item) => item.id == asset.id) .firstOrNull case final document?) AgentAttachmentCard( asset: document, onRemove: () => widget.composer.remove(asset.id), ) else InputChip( label: Text(asset.name), onDeleted: () => widget.composer.remove(asset.id), ), ], ), ), composerView, ], ), Positioned( top: 0, left: ComposerLayout.radius, right: ComposerLayout.radius, height: AppSpacing.small, child: Semantics( button: true, label: widget.expanded ? context.l10n.agentCollapseConversation : context.l10n.agentExpandConversation, onTap: widget.onToggleExpanded, child: Stack( fit: StackFit.expand, children: [ Center( child: Container( width: ComposerLayout.controlSize, height: 2, decoration: BoxDecoration( color: Theme.of(context) .colorScheme .onSurfaceVariant .withValues(alpha: .35), borderRadius: BorderRadius.circular( AppRadius.pill, ), ), ), ), WorkspaceResizeHandle( key: const Key('floating-agent-resize-handle'), axis: Axis.vertical, direction: -1, initialValue: _reveal.value * conversationHeight, onStart: _startResize, onResize: (height) { if (conversationHeight > 0) { _reveal.value = (height / conversationHeight) .clamp(0.0, 1.0); } }, onEnd: _finishResize, ), ], ), ), ), ], ), ), ), ); }, ); return AgentAttachmentDropRegion( projectId: projectId, composer: widget.composer, shrinkWrap: true, child: content, ); } }