import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_attachment_draft.dart'; import '../domain/chat_attachment_picker.dart'; import '../domain/chat_attachment_wire.dart'; import '../domain/chat_commands.dart'; import '../ui/sessions/chat_adaptive.dart'; import 'chat_command_palette.dart'; import 'chat_composer_controller.dart'; /// The composer's multiline placeholder, verbatim from the web client. const String chatComposerPlaceholder = 'Message the agent… or / for commands'; /// The single primary control's words while a turn is and is not running. const String chatSendLabel = 'Send'; const String chatStopLabel = 'Stop'; /// The attach control's accessible name, verbatim from the web composer. const String chatAttachLabel = 'Attach file'; /// The unknown-command report's two actions, verbatim from the web client. const String chatCommandSendAsMessageLabel = 'Send as message'; const String chatCommandCancelLabel = 'Cancel'; /// Shown while the reply says this prompt waits behind the running turn. const String chatQueuedNotice = 'Queued — it will send when the current turn finishes.'; /// The foot of one conversation: a native multiline field and one primary /// Send/Stop control, driven by the landed [ChatComposerController]. /// /// The field owns only its [TextEditingController] and focus; the durable draft /// text lives in the composer controller, so a live transcript rebuild never /// replaces the operator's caret. Enter inserts a newline and Ctrl/Cmd+Enter /// sends the plain message. A leading `/` opens the recorded command palette /// above the field: rows are filtered by name prefix, Up/Down move the /// highlight, Enter or a tap completes the highlighted command, Escape closes /// the palette. A slash draft is never handed to the prompt path: a completed /// command is not run yet (command actions are a later slice), and text naming /// no recorded command becomes the web client's local no-send report with its /// explicit "Send as message" offer. Picked files are memory-only chips: /// their names are shown with the host's own remove action and the bounded /// draft owns every refusal. Send carries the chips as the landed wire parts, /// keeps them until the prompt is accepted and leaves them in place on a /// refusal; paste is not wired. class ChatComposerBar extends StatefulWidget { const ChatComposerBar({ super.key, required this.composer, required this.running, this.picker, }); final ChatComposerController composer; /// The thread controller's running bit; it alone decides Send versus Stop. final bool running; /// The host picker seam; production uses [hostChatAttachmentPicker]. final ChatAttachmentPicker? picker; @override State createState() => _ChatComposerBarState(); } class _ChatComposerBarState extends State { late final TextEditingController _text = TextEditingController( text: widget.composer.draft, ); final FocusNode _focus = FocusNode(debugLabel: 'chat-composer'); final ChatAttachmentDraft _attachments = ChatAttachmentDraft(); /// The picked bytes behind each chip, positionally aligned with the draft's /// attachments so two picks of the same name stay distinct. final List _bytes = []; String? _attachmentError; /// The draft text whose palette the operator closed (Escape) or completed /// (a row or Enter). The palette stays hidden while the draft still equals /// it, so any further typing offers the commands again. String? _paletteClosedFor; /// The highlighted command row, wrapped to the filtered list on each build. int _selectedCommand = 0; /// The local no-send report shown under the field. Every slash draft takes /// this path instead of the prompt, as the web client records: an unknown /// command carries [_commandOffer] back for an explicit "Send as message". String? _commandNotice; String? _commandOffer; ChatAttachmentPicker get _picker => widget.picker ?? hostChatAttachmentPicker; @override void initState() { super.initState(); widget.composer.addListener(_syncDraft); unawaited(widget.composer.loadDraft()); } @override void didUpdateWidget(covariant ChatComposerBar oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.composer != widget.composer) { oldWidget.composer.removeListener(_syncDraft); widget.composer.addListener(_syncDraft); _syncDraft(); } } /// External draft changes (saved-draft load, send clear, refusal restore) /// replace the field's text but never the focus node, so the caret survives /// live transcript rebuilds. void _syncDraft() { if (!mounted) return; final draft = widget.composer.draft; if (_text.text == draft) return; _text.value = TextEditingValue( text: draft, selection: TextSelection.collapsed(offset: draft.length), ); } /// The recorded commands matching the current draft while the palette is /// open. A dismissed or completed draft keeps its palette closed until the /// operator types something newer. List _paletteCommands() { final draft = widget.composer.draft; if (_paletteClosedFor == draft) return const []; return chatCommandSuggestions(draft); } /// Mirrors the typed text into the composer after clearing the per-keystroke /// command state: a fresh edit reopens a dismissed palette, hides an old /// report, and resets the highlight when the filtered list no longer holds it /// (the web client's `refreshComposerControls`). void _onDraftEdited(String value) { final suggestions = chatCommandSuggestions(value); setState(() { _paletteClosedFor = null; _dismissCommandReport(); if (_selectedCommand >= suggestions.length) _selectedCommand = 0; }); unawaited(widget.composer.setDraft(value)); } KeyEventResult _onKey(FocusNode node, KeyEvent event) { final key = event.logicalKey; final commands = _paletteCommands(); final word = chatCommandWord(widget.composer.draft); final slashDraft = word != null; if (key == LogicalKeyboardKey.escape) { if (commands.isEmpty && _commandNotice == null) { return KeyEventResult.ignored; } if (event is KeyDownEvent) { setState(() { if (commands.isNotEmpty) _paletteClosedFor = widget.composer.draft; _dismissCommandReport(); }); } return KeyEventResult.handled; } if (commands.isNotEmpty && (key == LogicalKeyboardKey.arrowDown || key == LogicalKeyboardKey.arrowUp)) { if (event is! KeyDownEvent) return KeyEventResult.handled; final step = key == LogicalKeyboardKey.arrowDown ? 1 : -1; final selected = _selectedCommand % commands.length; setState(() => _selectedCommand = (selected + step) % commands.length); return KeyEventResult.handled; } if (key != LogicalKeyboardKey.enter && key != LogicalKeyboardKey.numpadEnter) { return KeyEventResult.ignored; } final keyboard = HardwareKeyboard.instance; final sendShortcut = keyboard.isControlPressed || keyboard.isMetaPressed; // A plain Enter accepts the highlighted command instead of sending it. With // no palette showing, a slash draft is still a command, never a prompt. if (!sendShortcut && !keyboard.isShiftPressed) { if (commands.isNotEmpty) { if (event is! KeyDownEvent) return KeyEventResult.handled; _completeCommand(commands[_selectedCommand % commands.length]); return KeyEventResult.handled; } if (slashDraft) { if (event is! KeyDownEvent) return KeyEventResult.handled; _runSlashDraft(); return KeyEventResult.handled; } } if (!sendShortcut) return KeyEventResult.ignored; // A held key must not post a second prompt. if (event is! KeyDownEvent) return KeyEventResult.handled; // Ctrl/Cmd+Enter is the same submit: a visible palette completes, and a // slash draft reports locally. Only plain text reaches the prompt path. if (commands.isNotEmpty) { _completeCommand(commands[_selectedCommand % commands.length]); return KeyEventResult.handled; } if (slashDraft) { _runSlashDraft(); return KeyEventResult.handled; } unawaited(_send()); return KeyEventResult.handled; } /// Routes the current slash draft to the command surface. Command actions /// are not implemented in this slice, so a recorded command reports that it /// is unavailable and keeps its draft; an unknown word takes the web client's /// report and consumes the draft into the offer. Neither posts a prompt. void _runSlashDraft() { final draft = widget.composer.draft; final word = chatCommandWord(draft); if (word == null) return; final command = chatCommandNamed(draft); if (command != null) { setState(() { _commandOffer = null; _commandNotice = chatCommandUnavailableReport('/${command.name}'); }); _focus.requestFocus(); return; } final offer = draft.trim(); setState(() { _commandOffer = offer; _commandNotice = chatUnknownCommandReport(word); }); _text.clear(); unawaited(widget.composer.setDraft('')); _focus.requestFocus(); } /// Closes whatever local command report is showing. Callers wrap this in /// [setState]; it owns no rebuild of its own. void _dismissCommandReport() { _commandNotice = null; _commandOffer = null; } /// The offer's one explicit route to the agent: take the reported draft back /// and send it as an ordinary message. The notice is dropped first, so a /// stale second tap sends nothing. Future _sendOffered() async { final offer = _commandOffer; if (offer == null) return; setState(_dismissCommandReport); if (offer != widget.composer.draft) { _text.value = TextEditingValue( text: offer, selection: TextSelection.collapsed(offset: offer.length), ); await widget.composer.setDraft(offer); if (!mounted) return; } await _send(); } /// Puts the chosen recorded command in the composer and closes the palette. /// Nothing is sent to the agent: selecting a command is completion, not an /// execution path (this slice adds the palette, not the command actions). void _completeCommand(ChatCommand command) { final text = '/${command.name}'; setState(() { _paletteClosedFor = text; _selectedCommand = 0; _dismissCommandReport(); }); _text.value = TextEditingValue( text: text, selection: TextSelection.collapsed(offset: text.length), ); unawaited(widget.composer.setDraft(text)); _focus.requestFocus(); } /// Builds the chips' exact wire parts and hands them to the composer with the /// draft's text and operation id. The chips stay while the prompt is in /// flight so a refusal leaves the draft and its files together; only an /// accepted prompt clears them. Future _send() async { final composer = widget.composer; if (composer.sending || composer.draft.trim().isEmpty) return; List parts; try { parts = chatAttachmentParts(_attachments, read: _readAttachment); } on ChatAttachmentWireException catch (error) { setState(() => _attachmentError = error.message); return; } // Keep the caret in the field while the prompt is in flight, as before. _focus.requestFocus(); final accepted = await composer.send(attachments: parts); if (!mounted) return; if (accepted) { setState(() { _replaceAttachments(const [], const []); _attachmentError = null; }); } } /// Adds the operator's explicit selection through the host seam. A dismissed /// picker changes nothing; a bounded draft refusal is shown in its own words /// while every attachment already in the draft stays. Future _pickAttachments() async { if (widget.composer.sending || !_picker.isSupported) return; List? files; try { files = await _picker.pick(); } catch (error) { if (!mounted) return; setState(() => _attachmentError = '$error'); return; } if (!mounted || files == null) return; final picked = files; setState(() { _attachmentError = null; for (final file in picked) { final attachment = file.attachment; final refusal = _attachments.add(attachment); if (refusal != null) { _attachmentError = refusal.message; } else { _bytes.add(file.bytes); } } }); } /// The picked bytes for the draft's own attachment instance. Identity is the /// only reliable match when two picks share a name, type and size. Uint8List? _readAttachment(ChatAttachment attachment) { final attachments = _attachments.attachments; for (var index = 0; index < attachments.length; index += 1) { if (identical(attachments[index], attachment)) return _bytes[index]; } return null; } void _removeAttachmentAt(int index) { setState(() { final remaining = List.from(_attachments.attachments) ..removeAt(index); final remainingBytes = List.from(_bytes)..removeAt(index); _replaceAttachments(remaining, remainingBytes); _attachmentError = null; }); } /// Rebuilds the draft and its aligned bytes in [attachments] order. The draft /// owns the count and size bounds, and every kept attachment already passed /// them, so re-adding never refuses. void _replaceAttachments( List attachments, List bytes, ) { for (final attachment in _attachments.attachments) { _attachments.remove(attachment); } _bytes ..clear() ..addAll(bytes); for (final attachment in attachments) { _attachments.add(attachment); } } @override void dispose() { widget.composer.removeListener(_syncDraft); _text.dispose(); _focus.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; return ListenableBuilder( listenable: widget.composer, builder: (context, _) { final composer = widget.composer; final error = composer.error ?? composer.draftError; final commands = _paletteCommands(); final selected = commands.isEmpty ? 0 : _selectedCommand % commands.length; return SafeArea( top: false, child: Padding( key: const Key('chat-composer'), padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 8), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (commands.isNotEmpty) Padding( padding: const EdgeInsetsDirectional.only(bottom: 8), child: ChatCommandPalette( commands: commands, selectedIndex: selected, onSelected: _completeCommand, ), ), if (!_attachments.isEmpty) _attachmentStrip(context, cupertino), if (_attachmentError != null) _notice( context, cupertino, key: const Key('chat-composer-attachment-error'), text: _attachmentError!, failed: true, ), if (_commandNotice != null) _commandReport(context, cupertino), if (composer.queued) _notice( context, cupertino, key: const Key('chat-composer-queued'), text: chatQueuedNotice, ), if (error != null) _notice( context, cupertino, key: const Key('chat-composer-error'), text: error, failed: true, ), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ _attach(context, cupertino), const SizedBox(width: 8), Expanded( child: Focus( canRequestFocus: false, includeSemantics: false, onKeyEvent: _onKey, child: _field(cupertino), ), ), const SizedBox(width: 8), _primary(context, cupertino), ], ), ], ), ), ); }, ); } /// The attach control: a host button that opens the picker, disabled when the /// host has no picker or one prompt is already awaiting its reply. Widget _attach(BuildContext context, bool cupertino) { final enabled = _picker.isSupported && !widget.composer.sending; final onPressed = enabled ? () => unawaited(_pickAttachments()) : null; if (cupertino) { return Semantics( label: chatAttachLabel, button: true, enabled: enabled, child: ExcludeSemantics( child: CupertinoButton( key: const Key('chat-composer-attach'), padding: EdgeInsets.zero, onPressed: onPressed, child: const Icon(CupertinoIcons.paperclip), ), ), ); } return IconButton( key: const Key('chat-composer-attach'), tooltip: chatAttachLabel, onPressed: onPressed, icon: const Icon(Icons.attach_file), ); } /// The files attached to the next message. Each chip carries only the /// operator's recorded name and a native remove action. Widget _attachmentStrip(BuildContext context, bool cupertino) { final attachments = _attachments.attachments; return Padding( key: const Key('chat-composer-attachments'), padding: const EdgeInsetsDirectional.only(bottom: 8), child: Wrap( spacing: 8, runSpacing: 4, children: [ for (var index = 0; index < attachments.length; index += 1) if (cupertino) _cupertinoChip(context, attachments[index], index) else _materialChip(attachments[index], index), ], ), ); } Widget _materialChip(ChatAttachment attachment, int index) => Chip( key: ValueKey('chat-composer-attachment-$index'), label: Text(attachment.name), onDeleted: () => _removeAttachmentAt(index), deleteButtonTooltipMessage: 'Remove ${attachment.name}', ); /// Cupertino has no chip control, so the host's capsule fill and its own /// button carry the same name and remove action. Widget _cupertinoChip( BuildContext context, ChatAttachment attachment, int index, ) { return Semantics( container: true, explicitChildNodes: true, child: DefaultTextStyle.merge( style: CupertinoTheme.of(context).textTheme.textStyle, child: DecoratedBox( key: ValueKey('chat-composer-attachment-$index'), decoration: ShapeDecoration( shape: const StadiumBorder(), color: CupertinoColors.secondarySystemFill.resolveFrom(context), ), child: Padding( padding: const EdgeInsetsDirectional.fromSTEB(12, 4, 4, 4), child: Row( mainAxisSize: MainAxisSize.min, children: [ Flexible( child: Text(attachment.name, overflow: TextOverflow.ellipsis), ), const SizedBox(width: 4), Semantics( container: true, button: true, label: 'Remove ${attachment.name}', onTap: () => _removeAttachmentAt(index), child: ExcludeSemantics( child: CupertinoButton( key: ValueKey( 'chat-composer-attachment-remove-$index', ), padding: EdgeInsets.zero, onPressed: () => _removeAttachmentAt(index), child: Icon( CupertinoIcons.xmark_circle_fill, color: CupertinoColors.secondaryLabel.resolveFrom( context, ), ), ), ), ), ], ), ), ), ), ); } Widget _field(bool cupertino) { if (cupertino) { return CupertinoTextField( key: const Key('chat-composer-field'), controller: _text, focusNode: _focus, placeholder: chatComposerPlaceholder, minLines: 1, maxLines: 6, keyboardType: TextInputType.multiline, textInputAction: TextInputAction.newline, onChanged: _onDraftEdited, ); } return TextField( key: const Key('chat-composer-field'), controller: _text, focusNode: _focus, minLines: 1, maxLines: 6, keyboardType: TextInputType.multiline, textInputAction: TextInputAction.newline, onChanged: _onDraftEdited, decoration: const InputDecoration( hintText: chatComposerPlaceholder, hintMaxLines: 1, border: OutlineInputBorder(), ), ); } Widget _primary(BuildContext context, bool cupertino) { final composer = widget.composer; final stop = widget.running; final enabled = stop ? !composer.stopping : !composer.sending && composer.draft.trim().isNotEmpty; void press() { if (stop) { unawaited(composer.stop()); return; } final commands = _paletteCommands(); if (commands.isNotEmpty) { _completeCommand(commands[_selectedCommand % commands.length]); } else if (chatCommandWord(composer.draft) != null) { _runSlashDraft(); } else { unawaited(_send()); } } final label = Text(stop ? chatStopLabel : chatSendLabel); if (cupertino) { return CupertinoButton( key: const Key('chat-composer-primary'), color: stop ? CupertinoColors.systemRed.resolveFrom(context) : null, onPressed: enabled ? press : null, child: label, ); } final scheme = Theme.of(context).colorScheme; return FilledButton( key: const Key('chat-composer-primary'), style: stop ? FilledButton.styleFrom( backgroundColor: scheme.error, foregroundColor: scheme.onError, ) : null, onPressed: enabled ? press : null, child: label, ); } /// The local command report: a failed line in the composer's own notice /// shape, plus the offer's two host controls when an unknown command can be /// sent as a message. Neither action is a prompt until the operator chooses /// "Send as message". Widget _commandReport(BuildContext context, bool cupertino) { final offer = _commandOffer; return Column( key: const Key('chat-composer-command-notice'), crossAxisAlignment: CrossAxisAlignment.stretch, children: [ _notice( context, cupertino, key: const Key('chat-composer-command-text'), text: _commandNotice!, failed: true, ), if (offer != null) Padding( padding: const EdgeInsetsDirectional.only(bottom: 8), child: Wrap( alignment: WrapAlignment.end, spacing: 8, runSpacing: 4, children: [ _commandAction( cupertino, key: const Key('chat-command-send-as-message'), label: chatCommandSendAsMessageLabel, onPressed: () => unawaited(_sendOffered()), ), _commandAction( cupertino, key: const Key('chat-command-cancel'), label: chatCommandCancelLabel, onPressed: () => setState(_dismissCommandReport), ), ], ), ), ], ); } Widget _commandAction( bool cupertino, { required Key key, required String label, required VoidCallback onPressed, }) { if (cupertino) { return CupertinoButton( key: key, padding: EdgeInsets.zero, onPressed: onPressed, child: Text(label), ); } return TextButton(key: key, onPressed: onPressed, child: Text(label)); } /// A polite, secondary line for queued/refused state. The error uses the /// host's own semantic error tint, never a bespoke palette. Widget _notice( BuildContext context, bool cupertino, { required Key key, required String text, bool failed = false, }) { final theme = Theme.of(context); final color = failed ? (cupertino ? CupertinoColors.systemRed.resolveFrom(context) : theme.colorScheme.error) : (cupertino ? CupertinoColors.secondaryLabel.resolveFrom(context) : theme.colorScheme.onSurfaceVariant); final style = (cupertino ? CupertinoTheme.of(context).textTheme.textStyle : theme.textTheme.bodyMedium) ?.copyWith(color: color); return Semantics( liveRegion: true, child: Padding( key: key, padding: const EdgeInsets.only(bottom: 8), child: Text(text, style: style), ), ); } }