Files
pipelines/app/lib/features/chat/conversation/chat_composer_bar.dart
T
alan 7ff012880b Add explicit surface visibility signal
Provide composable shown/current visibility for retained surfaces and migrate visibility readers away from TickerMode. This keeps ticker muting separate from painted and current-surface state.
2026-11-10 20:28:09 +00:00

1546 lines
56 KiB
Dart

import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../ui/scale/ui_scale.dart';
import '../../../ui/motion/surface_visibility.dart';
import 'chat_stop_icon.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/pipelines_client.dart';
import '../data/chat_attachment_images.dart';
import '../data/upload/chat_upload.dart';
import '../domain/chat_attachment_draft.dart';
import '../domain/chat_attachment_picker.dart';
import '../domain/chat_attachment_wire.dart';
import '../domain/chat_clipboard_paste.dart';
import '../domain/chat_commands.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_command_actions.dart';
import 'chat_command_palette.dart';
import 'chat_composer_controller.dart';
import 'chat_composer_paste_focus.dart';
import '../ui/transcript/chat_attachment_frame.dart';
import '../../../ui/adaptive/glass_bar.dart';
import '../../../ui/adaptive/glass_pill.dart';
import '../../../ui/adaptive/pop_entrance.dart';
import 'chat_reading_width.dart';
import 'composer_focus_request.dart';
import 'composer_focus_restore.dart';
import 'chat_bar_tint.dart';
import 'composer_focus_ring.dart';
import '../shell/chat_shell_command.dart';
import '../shell/chat_shell_mode_indicator.dart';
/// The composer's placeholder when the chat names no working directory.
const String chatComposerPlaceholder = 'Message the agent';
/// The composer's placeholder for a chat working in [directory]: its folder
/// name, as the operator would say it, or the generic placeholder without one.
String chatComposerPlaceholderFor(String directory) {
final parts = directory.trim().split(RegExp(r'[/\\]'));
final name = parts.lastWhere((part) => part.isNotEmpty, orElse: () => '');
return name.isEmpty ? chatComposerPlaceholder : 'Work on $name';
}
/// Whether Enter sends on [platform] (the running host by default).
///
/// On a phone the on-screen keyboard's Return breaks the line and the Send
/// button sends, as in other chat apps; a desktop keyboard's Enter sends and
/// Shift+Enter breaks the line. Ctrl/Cmd+Enter sends everywhere.
bool chatEnterSends([TargetPlatform? platform]) {
final target = platform ?? defaultTargetPlatform;
return target != TargetPlatform.android && target != TargetPlatform.iOS;
}
/// The composer's gap above the bottom of the window (or its bottom safe
/// area) on a phone, where it sits just over the keyboard or home indicator.
const double kChatComposerBottomMargin = 12;
/// The same gap on a desktop host (native or a desktop browser), whose
/// window's bottom edge is a hard frame under a pointer: the composer keeps
/// more room from it so it does not read as stuck to the edge.
const double kChatComposerDesktopBottomMargin = 24;
/// The composer's bottom gap on [platform] (the running host by default),
/// split between phones and desktops as [chatEnterSends] is.
double chatComposerBottomMargin([TargetPlatform? platform]) =>
chatEnterSends(platform)
? kChatComposerDesktopBottomMargin
: kChatComposerBottomMargin;
/// The single primary control's words while a turn is and is not running.
const String chatSendLabel = 'Send';
const String chatStopLabel = 'Stop';
/// The primary control's words while the draft is a `!` shell command.
const String chatRunShellLabel = 'Run command';
/// 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';
const String chatCommandNoticeLabel = 'Command';
const String chatCommandFailedLabel = 'Command failed';
const String chatCommandDismissLabel = 'Dismiss command notice';
/// The web's line after `/stop`'s interrupt was accepted.
const String chatStopCommandNotice = 'Stopping the running turn…';
/// 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 Send control,
/// with a separate Stop while a turn runs, driven by [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 sends, Shift+Enter inserts a newline,
/// and Ctrl/Cmd+Enter remains a send shortcut.
/// 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: `/new`,
/// `/close` and `/rename` run through [commands], `/stop` and `/help` run
/// locally or through the existing Stop path; 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. Pasting files takes the same draft path as the picker; pasting text
/// stays with the host field, so its caret, selection and draft behave exactly
/// as typing does.
class ChatComposerBar extends StatefulWidget {
const ChatComposerBar({
super.key,
required this.composer,
required this.running,
this.picker,
this.commands,
this.paste,
this.pasteTarget = true,
this.ownsPasteWhenFocused = false,
this.backgroundTasks,
this.runShell,
this.placeholder = chatComposerPlaceholder,
this.enterSends,
this.images,
this.chatColor,
});
/// The chat's colour name (see `chatSessionColor`), the accent of the
/// field's focus ring; null takes the host's primary colour.
final String? chatColor;
/// The transcript's image cache, told about uploaded files so the sent turn
/// shows them without a round trip.
final ChatAttachmentImages? images;
/// Overrides [chatEnterSends] for this composer; null follows the host.
final bool? enterSends;
final ChatComposerController composer;
/// The empty field's hint; see [chatComposerPlaceholderFor].
final String placeholder;
/// Runs `/new`, `/close` and `/rename` for the open session. A host without a
/// session (null) keeps those commands on the unavailable report.
final ChatCommandActions? commands;
/// The thread controller's running bit; shows Stop without hiding Send.
final bool running;
/// The host picker seam; production uses [hostChatAttachmentPicker].
final ChatAttachmentPicker? picker;
/// The host clipboard-file seam; production uses [hostChatClipboardPaste].
final ChatClipboardPaste? paste;
/// True only for the active visible pane.
final bool pasteTarget;
/// While its field has the keyboard this composer takes a paste (files
/// too) even when it is not [pasteTarget], and the paste target leaves it
/// alone: a floating chat over the tiled ones.
final bool ownsPasteWhenFocused;
final Widget? backgroundTasks;
/// Runs a `!` draft's command in the chat's folder (never a prompt);
/// resolves to the server's refusal, or null once it started. Null (no
/// session) reports shell mode as unavailable and sends nothing.
final Future<String?> Function(String command)? runShell;
@override
State<ChatComposerBar> createState() => _ChatComposerBarState();
}
class _ChatComposerBarState extends State<ChatComposerBar> {
late final TextEditingController _text = TextEditingController(
text: widget.composer.draft,
);
final FocusNode _focus = FocusNode(debugLabel: 'chat-composer');
/// The field's own scroll position, so a new last line is brought into
/// view as soon as it exists (see [_revealCaretLine]).
final ScrollController _fieldScroll = ScrollController();
late final ComposerFocusRestorer _focusRestorer;
late final ComposerFocusRequestListener _focusRequests =
ComposerFocusRequestListener(focus: _focus, canFocus: _composerIsCurrent);
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<Uint8List> _bytes = [];
String? _attachmentError;
/// True while the draft's files upload ahead of the prompt.
bool _uploading = false;
/// Upload names by attachment instance, so a retried send reuses the files
/// already stored instead of uploading them again.
final Expando<String> _uploaded = Expando();
/// 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;
bool _commandFailed = false;
/// True while a `!` command is being started.
bool _shellStarting = false;
ChatAttachmentPicker get _picker => widget.picker ?? hostChatAttachmentPicker;
ChatClipboardPaste get _paste => widget.paste ?? hostChatClipboardPaste;
ChatPasteUnsubscribe? _stopPaste;
/// The composer's accepted-send count the chips were last cleared for.
late int _seenAccepted = widget.composer.composerSendsAccepted;
@override
void initState() {
super.initState();
_focusRestorer = ComposerFocusRestorer(
focus: _focus,
canRestore: _composerIsCurrent,
);
widget.composer.addListener(_syncDraft);
ChatComposerPasteFocus.register(_focus);
ChatComposerPasteFocus.setOwnsFocusedPaste(
_focus,
widget.ownsPasteWhenFocused,
);
FocusManager.instance.addEarlyKeyEventHandler(_nativePasteKey);
_listenForPaste();
unawaited(widget.composer.loadDraft());
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_focusRequests.attach(context);
}
/// Whether the composer is still where the operator works: mounted, shown,
/// and not covered by a dialog, sheet or another pushed route.
bool _composerIsCurrent() =>
mounted &&
SurfaceVisibility.currentOf(context) &&
(ModalRoute.of(context)?.isCurrent ?? true);
@override
void didUpdateWidget(covariant ChatComposerBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.composer != widget.composer) {
oldWidget.composer.removeListener(_syncDraft);
widget.composer.addListener(_syncDraft);
_seenAccepted = widget.composer.composerSendsAccepted;
_syncDraft();
}
if (oldWidget.ownsPasteWhenFocused != widget.ownsPasteWhenFocused) {
ChatComposerPasteFocus.setOwnsFocusedPaste(
_focus,
widget.ownsPasteWhenFocused,
);
}
if (oldWidget.composer != widget.composer ||
oldWidget.paste != widget.paste ||
oldWidget.pasteTarget != widget.pasteTarget) {
_stopListeningForPaste();
_listenForPaste();
}
}
void _listenForPaste() {
if (!_paste.isSupported) return;
final owner = widget.composer;
_stopPaste = _paste.listen(
// File decoding is asynchronous. Keep an accepted paste on its original
// chat even if it becomes inactive, but never carry it to a replacement.
onFiles: (files) {
if (mounted && identical(widget.composer, owner)) _onPastedFiles(files);
},
canAccept: _canAcceptPaste,
onError: (error) {
if (mounted && identical(widget.composer, owner)) _onPasteError(error);
},
onText: _onPastedText,
canAcceptText: _canAcceptTextPaste,
);
}
void _stopListeningForPaste() {
final stop = _stopPaste;
_stopPaste = null;
stop?.call();
}
/// A pasted file is taken by the active, visible composer even when its
/// field is not focused. The host checks this before suppressing the paste's
/// default behaviour, so an inactive pane is never allowed to swallow it.
bool _canAcceptPaste() =>
mounted &&
(widget.ownsPasteWhenFocused && _focus.hasFocus ||
widget.pasteTarget &&
!ChatComposerPasteFocus.otherOwnerHasFocus(_focus)) &&
_composerIsCurrent() &&
!ChatComposerPasteFocus.anotherEditableHasFocus &&
!widget.composer.sending;
bool _canAcceptTextPaste() => _canAcceptPaste() && !_focus.hasFocus;
KeyEventResult _nativePasteKey(KeyEvent event) {
// Web uses the browser's clipboard event, never a second Clipboard read.
if (kIsWeb || event is! KeyDownEvent || !_canAcceptTextPaste()) {
return KeyEventResult.ignored;
}
final keys = HardwareKeyboard.instance;
if (event.logicalKey != LogicalKeyboardKey.keyV ||
keys.isAltPressed ||
keys.isShiftPressed ||
!(keys.isControlPressed != keys.isMetaPressed)) {
return KeyEventResult.ignored;
}
unawaited(_readNativePaste());
return KeyEventResult.handled;
}
Future<void> _readNativePaste() async {
try {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text;
if (text != null && text.isNotEmpty) _onPastedText(text);
} catch (_) {
if (mounted && _canAcceptPaste()) {
_onPasteError('Could not read clipboard text.');
}
}
}
void _onPastedText(String text) {
// Recheck after an asynchronous native read, but permit the same composer
// to have received focus meanwhile. Never insert into another editor.
if (!mounted || !_canAcceptPaste()) return;
final value = _text.value;
final selection = value.selection.isValid
? value.selection
: TextSelection.collapsed(offset: value.text.length);
final next = value.text.replaceRange(selection.start, selection.end, text);
_text.value = TextEditingValue(
text: next,
selection: TextSelection.collapsed(offset: selection.start + text.length),
);
_onDraftEdited(next);
_focus.requestFocus();
}
void _onPastedFiles(List<ChatPickedFile> files) {
if (!mounted) return;
_addFiles(files);
}
void _onPasteError(Object error) {
if (!mounted) return;
setState(() => _attachmentError = '$error');
}
/// 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 accepted = widget.composer.composerSendsAccepted;
if (accepted != _seenAccepted) {
_seenAccepted = accepted;
setState(() {
_replaceAttachments(const [], const []);
_attachmentError = null;
});
}
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<ChatCommand> _paletteCommands() {
final draft = widget.composer.draft;
if (_paletteClosedFor == draft) return const <ChatCommand>[];
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));
_revealCaretLine(value);
}
/// At the field's line limit, a newline at the end leaves the caret on a
/// new empty line the field only scrolls to once it has a character.
/// Scroll there right away whenever the caret is at the end.
void _revealCaretLine(String value) {
final caret = _text.selection;
if (!caret.isCollapsed || caret.baseOffset != value.length) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_fieldScroll.hasClients) return;
final position = _fieldScroll.position;
if (position.pixels < position.maxScrollExtent) {
_fieldScroll.jumpTo(position.maxScrollExtent);
}
});
}
KeyEventResult _onKey(FocusNode node, KeyEvent event) {
final key = event.logicalKey;
final commands = _paletteCommands();
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;
// Enter may be confirming an IME candidate rather than submitting a draft.
if (_text.value.composing.isValid && !_text.value.composing.isCollapsed) {
return KeyEventResult.ignored;
}
// A phone keyboard's Return is the field's own newline; only the
// modifier shortcut sends from the keyboard there.
if (!sendShortcut && !_enterSends) return KeyEventResult.ignored;
if (!sendShortcut && keyboard.isShiftPressed) {
if (event is KeyDownEvent) {
final selection = _text.selection;
final start = selection.isValid ? selection.start : _text.text.length;
final end = selection.isValid ? selection.end : start;
_text.value = TextEditingValue(
text: _text.text.replaceRange(start, end, '\n'),
selection: TextSelection.collapsed(offset: start + 1),
);
_onDraftEdited(_text.text);
}
return KeyEventResult.handled;
}
if (!sendShortcut && keyboard.isAltPressed) {
return KeyEventResult.ignored;
}
// A held key must not post a second prompt.
if (event is! KeyDownEvent) return KeyEventResult.handled;
_submitDraft();
return KeyEventResult.handled;
}
bool get _enterSends => widget.enterSends ?? chatEnterSends();
/// Hardware Enter, the keyboard's Send action and modifier shortcuts share
/// the same command/prompt path. An active IME candidate is never submitted.
void _submitDraft() {
if (_text.value.composing.isValid && !_text.value.composing.isCollapsed) {
return;
}
final keyboard = HardwareKeyboard.instance;
if (!keyboard.isControlPressed &&
!keyboard.isMetaPressed &&
(keyboard.isShiftPressed || keyboard.isAltPressed)) {
return;
}
final commands = _paletteCommands();
if (commands.isNotEmpty) {
_completeCommand(commands[_selectedCommand % commands.length]);
return;
}
if (chatDraftIsShell(widget.composer.draft)) {
unawaited(_runShellDraft());
return;
}
if (chatCommandWord(widget.composer.draft) != null) {
_runSlashDraft();
return;
}
unawaited(_send());
}
/// A `!` draft runs as a shell command and is never sent to the agent. The
/// draft is cleared once the server started it; a refusal keeps it.
Future<void> _runShellDraft() async {
final draft = widget.composer.draft;
final command = chatShellCommandOf(draft) ?? '';
final run = widget.runShell;
if (run == null) {
_showCommandNotice(
'Shell commands are not available here, so nothing was sent.',
failed: true,
);
return;
}
if (command.isEmpty) {
_showCommandNotice('Type a command after !.', failed: true);
return;
}
if (_shellStarting) return;
setState(() {
_shellStarting = true;
_dismissCommandReport();
});
final refusal = await run(command);
if (!mounted) return;
setState(() => _shellStarting = false);
if (refusal != null) {
_showCommandNotice(refusal, failed: true);
return;
}
if (widget.composer.draft == draft) _consumeCommandDraft();
}
/// Routes a slash draft locally or through the existing Stop controller path.
void _runSlashDraft() {
final draft = widget.composer.draft;
final word = chatCommandWord(draft);
if (word == null) return;
final command = chatCommandNamed(draft);
final actions = widget.commands;
if (command != null) {
final argument = chatCommandArgument(draft);
if (!command.takesArgument && argument.isNotEmpty) {
_consumeCommandDraft();
_showCommandNotice(
'${command.usage} does not take an argument.',
failed: true,
);
} else if (actions != null && ChatCommandActions.runs(command)) {
_consumeCommandDraft();
setState(_dismissCommandReport);
unawaited(actions.run(command, argument));
} else if (command.name == chatCommandStop) {
_consumeCommandDraft();
if (widget.running) {
unawaited(_stopFromCommand());
} else {
_showCommandNotice('No turn is running in this chat.', failed: true);
}
} else if (command.name == chatCommandHelp) {
_consumeCommandDraft();
_showCommandNotice(chatCommandHelpText());
} else {
_consumeCommandDraft();
_showCommandNotice(chatCommandUnavailableReport('/${command.name}'));
}
return;
}
final offer = draft.trim();
setState(() {
_commandFailed = true;
_commandOffer = offer;
_commandNotice = chatUnknownCommandReport(word);
});
_text.clear();
unawaited(widget.composer.setDraft(''));
_focus.requestFocus();
}
/// `/stop`'s accepted interrupt reports the web's line; a refusal is the
/// composer's own error.
Future<void> _stopFromCommand() async {
await widget.composer.stop();
if (!mounted || widget.composer.error != null) return;
_showCommandNotice(chatStopCommandNotice);
}
void _consumeCommandDraft() {
_text.clear();
unawaited(widget.composer.setDraft(''));
_focus.requestFocus();
}
void _showCommandNotice(String text, {bool failed = false}) {
setState(() {
_commandFailed = failed;
_commandOffer = null;
_commandNotice = text;
});
}
/// 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;
_commandFailed = false;
}
/// 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<void> _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<void> _send() async {
final composer = widget.composer;
if (_uploading || composer.sending || composer.draft.trim().isEmpty) {
return;
}
List<JsonMap> parts;
final endpoint = configuredGatewayEndpoint(composer.gateway);
try {
if (endpoint.isEmpty || _attachments.isEmpty) {
parts = chatAttachmentParts(_attachments, read: _readAttachment);
} else {
// Each file goes to the server as its own request first; the prompt
// then names the stored files.
setState(() {
_uploading = true;
_attachmentError = null;
});
parts = await chatAttachmentUploadParts(
_attachments,
read: _readAttachment,
upload: (attachment, bytes) async {
final stored = _uploaded[attachment] ??= await uploadChatAttachment(
endpoint,
attachment,
bytes,
);
// The sent turn draws these bytes instead of fetching them back.
if (attachment.mime.toLowerCase().startsWith('image/')) {
widget.images?.rememberUpload(stored, bytes);
}
return stored;
},
);
}
} on ChatAttachmentWireException catch (error) {
if (mounted) {
setState(() {
_uploading = false;
_attachmentError = error.message;
});
}
return;
}
if (!mounted) return;
if (_uploading) setState(() => _uploading = false);
// Keep the caret in the field while the prompt is in flight, as before.
_focus.requestFocus();
// Acceptance (here or through the bubble's Retry) clears the chips via
// the composer's accepted-send count.
await composer.send(attachments: parts);
}
/// 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<void> _pickAttachments() async {
if (widget.composer.sending || !_picker.isSupported) return;
List<ChatPickedFile>? files;
try {
files = await _picker.pick();
} catch (error) {
if (!mounted) return;
setState(() => _attachmentError = '$error');
return;
}
if (!mounted || files == null) return;
_addFiles(files);
}
/// Adds each file through the landed attachment draft. A refusal keeps every
/// attachment already in the draft and shows the draft's own words; the
/// refused file's bytes are never retained. Picking and pasting share this
/// path so both apply the same name and size decisions.
void _addFiles(List<ChatPickedFile> files) {
if (!mounted) return;
setState(() {
_attachmentError = null;
for (final file in files) {
final refusal = _attachments.add(file.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<ChatAttachment>.from(_attachments.attachments)
..removeAt(index);
final remainingBytes = List<Uint8List>.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<ChatAttachment> attachments,
List<Uint8List> 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() {
_stopListeningForPaste();
FocusManager.instance.removeEarlyKeyEventHandler(_nativePasteKey);
ChatComposerPasteFocus.unregister(_focus);
widget.composer.removeListener(_syncDraft);
_focusRestorer.dispose();
_focusRequests.dispose();
_text.dispose();
_focus.dispose();
_fieldScroll.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;
// Everything the next message carries (attachments, its notices) sits
// inside the glass with the field, as one floating composer; only the
// command palette, a separate menu, floats above it.
final extras = <Widget>[
if (chatDraftIsShell(composer.draft))
ChatShellModeIndicator(cupertino: cupertino),
if (!_attachments.isEmpty) _attachmentStrip(context, cupertino),
if (_uploading)
_notice(
context,
cupertino,
key: const Key('chat-composer-uploading'),
text: _attachments.attachments.length == 1
? 'Uploading 1 file…'
: 'Uploading ${_attachments.attachments.length} files…',
),
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,
),
];
return SafeArea(
top: false,
// The composer floats over the transcript in the conversation's
// centred reading column; the space beside it passes taps through.
child: Align(
heightFactor: 1,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: kChatReadingWidth),
child: Padding(
key: const Key('chat-composer'),
padding: EdgeInsetsDirectional.fromSTEB(
16,
8,
16,
chatComposerBottomMargin(),
),
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,
),
),
// The pill pops in with the app's shared entrance, as
// the bar's pieces do, once per chat: this state is keyed
// by the chat, and a rebuild (typing, the keyboard, a
// sheet closing) never replays it. It only paints, so the
// field takes focus and keys at once while it plays.
PopEntrance(
key: const ValueKey('chat-composer-entrance'),
child: _pill(
context,
cupertino,
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (extras.isNotEmpty)
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
12,
8,
12,
0,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment:
CrossAxisAlignment.stretch,
children: extras,
),
),
LayoutBuilder(
builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_attach(context, cupertino),
Expanded(
child: Focus(
canRequestFocus: false,
includeSemantics: false,
onKeyEvent: _onKey,
child: _field(cupertino),
),
),
// Shown only while tasks run (or their list
// cannot be read); a quiet control, not a
// caption.
if (widget.backgroundTasks != null)
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: constraints.maxWidth * .30,
),
child: widget.backgroundTasks!,
),
if (widget.running) ...[
_primary(context, cupertino, stop: true),
const SizedBox(width: 4),
],
_primary(context, cupertino),
],
),
),
],
),
),
),
],
),
),
),
),
);
},
);
}
static const OutlinedBorder _pillShape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(28)),
);
/// The field and its controls in one frosted-glass surface floating over
/// the transcript, so the composer reads as a single input rather than a
/// row of separate controls, and the conversation shows through it. While
/// the field has focus a ring in the chat's colour runs along its edge.
Widget _pill(BuildContext context, bool cupertino, Widget child) =>
ComposerFocusRing(
focus: _focus,
accent: chatFocusRingColor(context, widget.chatColor),
shape: _pillShape,
child: GlassPill(
key: const Key('chat-composer-pill'),
cupertino: cupertino,
shape: _pillShape,
// The end controls keep the same gap from the pill's sides as from
// its bottom (and its top while the field is one line).
child: Padding(
padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap),
child: child,
),
),
);
/// 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,
minimumSize: GlassBarMetrics.cupertinoMinimumSize(),
onPressed: onPressed,
child: const Icon(CupertinoIcons.add),
),
),
);
}
return IconButton(
key: const Key('chat-composer-attach'),
tooltip: chatAttachLabel,
onPressed: onPressed,
icon: const Icon(Icons.add),
);
}
/// 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 (_imageBytes(index) case final bytes?)
_imageThumbnail(context, attachments[index], bytes, index)
else if (cupertino)
_cupertinoChip(context, attachments[index], index)
else
_materialChip(attachments[index], index),
],
),
);
}
/// The pasted or picked bytes of an image attachment, or null for any other
/// file.
Uint8List? _imageBytes(int index) {
final attachment = _attachments.attachments[index];
if (!attachment.mime.toLowerCase().startsWith('image/')) return null;
if (index >= _bytes.length || _bytes[index].isEmpty) return null;
return _bytes[index];
}
/// An image attachment as a small thumbnail with its remove control in the
/// corner; its name is the accessible label.
Widget _imageThumbnail(
BuildContext context,
ChatAttachment attachment,
Uint8List bytes,
int index,
) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return Semantics(
key: ValueKey<String>('chat-composer-attachment-$index'),
container: true,
explicitChildNodes: true,
label: attachment.name,
image: true,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox.square(
dimension: 72,
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned.fill(
child: ChatAttachmentFrame(
radius: BorderRadius.circular(10),
child: Image.memory(
bytes,
key: ValueKey<String>('chat-composer-thumbnail-$index'),
fit: BoxFit.cover,
errorBuilder: (_, _, _) => Center(
child: Icon(
cupertino
? CupertinoIcons.photo
: Icons.image_outlined,
),
),
),
),
),
Positioned(
top: -6,
right: -6,
child: Semantics(
button: true,
label: 'Remove ${attachment.name}',
onTap: () => _removeAttachmentAt(index),
child: ExcludeSemantics(
child: GestureDetector(
key: ValueKey<String>(
'chat-composer-attachment-remove-$index',
),
onTap: () => _removeAttachmentAt(index),
child: Container(
decoration: const BoxDecoration(
color: Color(0xCC000000),
shape: BoxShape.circle,
),
padding: const EdgeInsets.all(2),
child: Icon(
cupertino ? CupertinoIcons.xmark : Icons.close,
size: 14,
color: const Color(0xFFFFFFFF),
),
),
),
),
),
),
],
),
),
// The name under the picture, one line.
SizedBox(
width: 72,
child: Text(
attachment.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 11),
),
),
],
),
);
}
Widget _materialChip(ChatAttachment attachment, int index) => Chip(
key: ValueKey<String>('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<String>('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<String>(
'chat-composer-attachment-remove-$index',
),
padding: EdgeInsets.zero,
onPressed: () => _removeAttachmentAt(index),
child: Icon(
CupertinoIcons.xmark_circle_fill,
color: CupertinoColors.secondaryLabel.resolveFrom(
context,
),
),
),
),
),
],
),
),
),
),
);
}
/// The lines the composer placeholder needs at [width] (the field's
/// default 7px side padding excluded), capped at 3.
int _placeholderLines(BuildContext context, double width) {
if (!width.isFinite) return 1;
final painter = TextPainter(
text: TextSpan(
text: widget.placeholder,
style: CupertinoTheme.of(context).textTheme.textStyle,
),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
maxLines: 3,
)..layout(maxWidth: math.max(0, width - 14));
final lines = painter.computeLineMetrics().length;
painter.dispose();
return lines.clamp(1, 3);
}
/// The most lines the field grows to before it scrolls: up to
/// [_composerMaxLines], but never more than about 40% of the visible
/// height (the keyboard excluded), so the conversation stays in view.
static const int _composerMaxLines = 12;
int _maxLines(BuildContext context) {
final media = MediaQuery.of(context);
// The scaffold hides the keyboard from its body; the window still has it.
final keyboard =
MediaQueryData.fromView(View.of(context)).viewInsets.bottom /
UiScaleHost.of(context);
final visible = media.size.height - keyboard;
final lineHeight = MediaQuery.textScalerOf(context).scale(22);
final fit = (visible * 0.4 / lineHeight).floor();
return fit.clamp(3, _composerMaxLines);
}
Widget _field(bool cupertino) {
final maxLines = _maxLines(context);
if (cupertino) {
// CupertinoTextField lays its placeholder out with up to maxLines lines
// but sizes an empty field by minLines, so a wrapped placeholder was
// clipped on a narrow pane. While empty the field is exactly as tall as
// its placeholder (at most 3 lines, then ellipsised); typing restores
// the normal range (see _maxLines).
return LayoutBuilder(
builder: (context, constraints) {
final empty = _text.text.isEmpty;
final lines = empty
? _placeholderLines(context, constraints.maxWidth)
: 1;
return CupertinoTextField(
key: const Key('chat-composer-field'),
controller: _text,
focusNode: _focus,
scrollController: _fieldScroll,
placeholder: widget.placeholder,
// The pill draws the field's surface; the field adds no border.
decoration: null,
// The contextual prompt must stay readable on the glass fill;
// placeholderText falls below normal-text contrast here.
placeholderStyle: TextStyle(
color: CupertinoColors.label.resolveFrom(context),
overflow: TextOverflow.ellipsis,
),
minLines: lines,
// Keep the empty field multiline too: a single-line web editor
// strips Shift+Enter's newline on the next text edit.
maxLines: empty && lines > 1 ? lines : maxLines,
keyboardType: TextInputType.multiline,
textInputAction: _enterSends
? TextInputAction.send
: TextInputAction.newline,
onEditingComplete: () {},
onSubmitted: (_) => _submitDraft(),
onChanged: _onDraftEdited,
);
},
);
}
return TextField(
key: const Key('chat-composer-field'),
controller: _text,
focusNode: _focus,
scrollController: _fieldScroll,
minLines: 1,
maxLines: maxLines,
keyboardType: TextInputType.multiline,
textInputAction: _enterSends
? TextInputAction.send
: TextInputAction.newline,
onEditingComplete: () {},
onSubmitted: (_) => _submitDraft(),
onChanged: _onDraftEdited,
decoration: InputDecoration(
hintText: widget.placeholder,
// Let a long folder name wrap when the attach and primary controls
// leave little horizontal room.
hintMaxLines: 2,
// The pill draws the field's surface; the field adds no border.
border: InputBorder.none,
isDense: true,
contentPadding: const EdgeInsets.symmetric(vertical: 12),
),
);
}
Widget _primary(BuildContext context, bool cupertino, {bool stop = false}) {
final composer = widget.composer;
final enabled = stop
? !composer.stopping
: !_uploading &&
!_shellStarting &&
!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 (chatDraftIsShell(composer.draft)) {
unawaited(_runShellDraft());
} else if (chatCommandWord(composer.draft) != null) {
_runSlashDraft();
} else {
unawaited(_send());
}
}
// Sending while the turn runs uses the server's existing queued-prompt path.
// Stopping is always a separate, explicitly named action.
final label = stop
? chatStopLabel
: chatDraftIsShell(composer.draft)
? chatRunShellLabel
: chatSendLabel;
final key = Key(stop ? 'chat-composer-stop' : 'chat-composer-primary');
// A coloured chat's send button takes the chat's colour (its seeded
// primary, like the focus ring); stop stays the host's error red.
final tinted = chatSchemeOf(context, widget.chatColor);
if (cupertino) {
return Semantics(
button: true,
label: label,
excludeSemantics: true,
// A filled circle centred in a full touch target, like Material's
// filled icon button, so it keeps the pill's edge gap on every side.
child: SizedBox.square(
dimension: GlassBarMetrics.controlExtent(true),
child: Center(
child: CupertinoButton.filled(
key: key,
sizeStyle: CupertinoButtonSize.small,
padding: EdgeInsets.zero,
minimumSize: Size.square(GlassBarMetrics.filledExtent(true)),
borderRadius: BorderRadius.circular(
GlassBarMetrics.filledExtent(true) / 2,
),
color: stop
? CupertinoColors.systemRed.resolveFrom(context)
: tinted?.primary,
onPressed: enabled ? press : null,
child: stop
? const ChatStopIcon(
child: Icon(CupertinoIcons.stop_fill, size: 18),
)
: Icon(
CupertinoIcons.arrow_up,
size: 18,
color: enabled ? tinted?.onPrimary : null,
),
),
),
),
);
}
final scheme = Theme.of(context).colorScheme;
return IconButton.filled(
key: key,
tooltip: label,
style: stop
? IconButton.styleFrom(
backgroundColor: scheme.error,
foregroundColor: scheme.onError,
)
: tinted == null
? null
: IconButton.styleFrom(
backgroundColor: tinted.primary,
foregroundColor: tinted.onPrimary,
),
onPressed: enabled ? press : null,
icon: stop
? const ChatStopIcon(child: Icon(Icons.stop))
: const Icon(Icons.arrow_upward),
);
}
/// 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: [
Row(
children: [
Expanded(
child: Text(
_commandFailed
? chatCommandFailedLabel
: chatCommandNoticeLabel,
style: TextStyle(
color: _commandFailed
? (cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error)
: null,
),
),
),
if (cupertino)
Semantics(
button: true,
label: chatCommandDismissLabel,
child: CupertinoButton(
key: const Key('chat-command-dismiss'),
padding: EdgeInsets.zero,
onPressed: () => setState(_dismissCommandReport),
child: const Text('Dismiss'),
),
)
else
IconButton(
key: const Key('chat-command-dismiss'),
tooltip: chatCommandDismissLabel,
onPressed: () => setState(_dismissCommandReport),
icon: const Icon(Icons.close),
),
],
),
_notice(
context,
cupertino,
key: const Key('chat-composer-command-text'),
text: _commandNotice!,
failed: _commandFailed,
),
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),
),
);
}
}