diff --git a/app/lib/features/chat/conversation/chat_command_palette.dart b/app/lib/features/chat/conversation/chat_command_palette.dart new file mode 100644 index 00000000..5cd2acff --- /dev/null +++ b/app/lib/features/chat/conversation/chat_command_palette.dart @@ -0,0 +1,127 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/chat_commands.dart'; +import '../ui/sessions/chat_adaptive.dart'; + +/// The command palette above the composer: the recorded commands matching the +/// slash word, each with its own `/name` and summary. +/// +/// Rows are standard host controls (Material's selected `ListTile`, Cupertino's +/// own button on a popup surface), so typography, colours and text scaling stay +/// the platform's. The list is content-sized and never imposes a fixed height; +/// a viewport-bound scroll keeps a tall text scale reachable. +class ChatCommandPalette extends StatelessWidget { + const ChatCommandPalette({ + super.key, + required this.commands, + required this.selectedIndex, + required this.onSelected, + }); + + final List commands; + + /// The highlighted row. Callers clamp it to this list. + final int selectedIndex; + + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + if (commands.isEmpty) return const SizedBox.shrink(); + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final list = cupertino ? _cupertinoRows(context) : _materialRows(context); + return ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.4, + ), + child: SingleChildScrollView( + child: Semantics( + container: true, + label: 'Command suggestions', + child: list, + ), + ), + ); + } + + Widget _materialRows(BuildContext context) { + return Card( + key: const Key('chat-command-palette'), + margin: EdgeInsets.zero, + clipBehavior: Clip.antiAlias, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (var index = 0; index < commands.length; index += 1) + ListTile( + key: ValueKey('chat-command-${commands[index].name}'), + selected: index == selectedIndex, + title: Text('/${commands[index].name}'), + subtitle: Text(commands[index].summary), + onTap: () => onSelected(commands[index]), + ), + ], + ), + ); + } + + /// Cupertino has no list tile that keeps a wrapping summary, so each row is + /// the host's own button, with the name and summary at the native text style + /// and the selected row on the host's semantic fill. + Widget _cupertinoRows(BuildContext context) { + final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + final selectedFill = CupertinoColors.systemFill.resolveFrom(context); + final textStyle = CupertinoTheme.of(context).textTheme.textStyle; + return CupertinoPopupSurface( + key: const Key('chat-command-palette'), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (var index = 0; index < commands.length; index += 1) + Semantics( + selected: index == selectedIndex, + child: SizedBox( + width: double.infinity, + child: CupertinoButton( + key: ValueKey('chat-command-${commands[index].name}'), + padding: EdgeInsets.zero, + onPressed: () => onSelected(commands[index]), + child: SizedBox( + width: double.infinity, + child: DecoratedBox( + decoration: BoxDecoration( + color: index == selectedIndex ? selectedFill : null, + ), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB( + 16, + 10, + 16, + 10, + ), + child: DefaultTextStyle.merge( + style: textStyle, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('/${commands[index].name}'), + Text( + commands[index].summary, + style: TextStyle(color: secondary), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 00f41864..3b2a2089 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -8,7 +8,9 @@ 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. @@ -21,6 +23,10 @@ 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.'; @@ -31,11 +37,17 @@ const String chatQueuedNotice = /// 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. 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. +/// 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, @@ -68,6 +80,20 @@ class _ChatComposerBarState extends State { 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 @@ -100,21 +126,162 @@ class _ChatComposerBarState extends State { ); } + /// 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) { - if (event.logicalKey != LogicalKeyboardKey.enter && - event.logicalKey != LogicalKeyboardKey.numpadEnter) { + 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; - if (!keyboard.isControlPressed && !keyboard.isMetaPressed) { - return KeyEventResult.ignored; + 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 @@ -225,6 +392,10 @@ class _ChatComposerBarState extends State { 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( @@ -234,6 +405,15 @@ class _ChatComposerBarState extends State { 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( @@ -243,6 +423,7 @@ class _ChatComposerBarState extends State { text: _attachmentError!, failed: true, ), + if (_commandNotice != null) _commandReport(context, cupertino), if (composer.queued) _notice( context, @@ -396,8 +577,6 @@ class _ChatComposerBarState extends State { } Widget _field(bool cupertino) { - final composer = widget.composer; - void changed(String value) => unawaited(composer.setDraft(value)); if (cupertino) { return CupertinoTextField( key: const Key('chat-composer-field'), @@ -408,7 +587,7 @@ class _ChatComposerBarState extends State { maxLines: 6, keyboardType: TextInputType.multiline, textInputAction: TextInputAction.newline, - onChanged: changed, + onChanged: _onDraftEdited, ); } return TextField( @@ -419,7 +598,7 @@ class _ChatComposerBarState extends State { maxLines: 6, keyboardType: TextInputType.multiline, textInputAction: TextInputAction.newline, - onChanged: changed, + onChanged: _onDraftEdited, decoration: const InputDecoration( hintText: chatComposerPlaceholder, hintMaxLines: 1, @@ -437,6 +616,13 @@ class _ChatComposerBarState extends State { 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()); } @@ -465,6 +651,67 @@ class _ChatComposerBarState extends State { ); } + /// 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( diff --git a/app/lib/features/chat/domain/chat_commands.dart b/app/lib/features/chat/domain/chat_commands.dart new file mode 100644 index 00000000..d93ebd31 --- /dev/null +++ b/app/lib/features/chat/domain/chat_commands.dart @@ -0,0 +1,120 @@ +/// One command the chat composer offers. [name] is the word after the slash, +/// [usage] is what the operator types (including any argument) and [summary] is +/// the few-word description shown beside it. [takesArgument] is false for the +/// commands that act on the current session alone. +/// +/// The words and order are the web client's `CHAT_COMMANDS`, which the Android +/// client records too. They are a fixed client-side vocabulary, not server data. +class ChatCommand { + const ChatCommand({ + required this.name, + required this.summary, + required this.usage, + this.takesArgument = false, + }); + + final String name; + final String summary; + final String usage; + final bool takesArgument; +} + +const String chatCommandNew = 'new'; +const String chatCommandClose = 'close'; +const String chatCommandRename = 'rename'; +const String chatCommandStop = 'stop'; +const String chatCommandHelp = 'help'; + +/// The recorded command list, in the order the palette shows it. +const List chatCommands = [ + ChatCommand( + name: chatCommandNew, + summary: 'Start a fresh session in this directory', + usage: '/new', + ), + ChatCommand( + name: chatCommandClose, + summary: 'Finish this session for every client, keeping its history', + usage: '/close', + ), + ChatCommand( + name: chatCommandRename, + summary: 'Rename this session on this device', + usage: '/rename ', + takesArgument: true, + ), + ChatCommand( + name: chatCommandStop, + summary: 'Stop the turn that is running', + usage: '/stop', + ), + ChatCommand( + name: chatCommandHelp, + summary: 'List every command', + usage: '/help', + ), +]; + +final RegExp _whitespace = RegExp(r'\s'); + +/// The lower-case name prefix a draft offers commands for, or null when the +/// draft is not a single slash word. +/// +/// Only the start of the draft counts. Once whitespace follows the word an +/// argument has begun, so the palette hides; text that does not start with a +/// slash offers nothing. +String? chatCommandQuery(String draft) { + final trimmed = draft.trimLeft(); + if (!trimmed.startsWith('/')) return null; + if (_whitespace.hasMatch(trimmed)) return null; + return trimmed.substring(1).toLowerCase(); +} + +/// The recorded commands matching [draft], filtered case-insensitively by name +/// prefix. Empty when no palette should show. +List<ChatCommand> chatCommandSuggestions(String draft) { + final query = chatCommandQuery(draft); + if (query == null) return const <ChatCommand>[]; + return <ChatCommand>[ + for (final command in chatCommands) + if (command.name.toLowerCase().startsWith(query)) command, + ]; +} + +/// The slash word [draft] starts with, including its `/`, or null when the +/// draft does not start with one. Only the first word counts, so an argument +/// (`/rename My chat`) still names `/rename`. +String? chatCommandWord(String draft) { + final trimmed = draft.trimLeft(); + if (!trimmed.startsWith('/')) return null; + final boundary = _whitespace.firstMatch(trimmed); + return boundary == null ? trimmed : trimmed.substring(0, boundary.start); +} + +/// The recorded command [draft] names, matched case-insensitively against the +/// whole slash word, or null when that word names no recorded command. +/// +/// This is the routing question, not the palette filter: a completed command +/// (`/close`) and one carrying its argument (`/rename My chat`) both resolve. +ChatCommand? chatCommandNamed(String draft) { + final word = chatCommandWord(draft); + if (word == null) return null; + final name = word.substring(1).toLowerCase(); + for (final command in chatCommands) { + if (command.name.toLowerCase() == name) return command; + } + return null; +} + +/// The local no-send report for a slash draft naming no recorded command, +/// verbatim from the web client's unknown-command notice. The report offers the +/// draft back, so only an explicit "Send as message" reaches the agent. +String chatUnknownCommandReport(String word) => + '“$word” is not a command, so nothing was sent to the agent. ' + 'Send it as a message, or cancel.'; + +/// The local no-send report for a recorded command whose action this client +/// does not run yet. Command actions are a later slice; until they land the +/// text must never become an implicit prompt. +String chatCommandUnavailableReport(String word) => + '“$word” is not available yet, so nothing was sent to the agent.'; diff --git a/app/notes/C9-commands.md b/app/notes/C9-commands.md new file mode 100644 index 00000000..09e70f2f --- /dev/null +++ b/app/notes/C9-commands.md @@ -0,0 +1,45 @@ +# C9 — slash command palette and no-send routing + +Status: palette and routing landed in the Flutter app; command *actions* +(`/new`, `/close`, `/rename`, `/stop`, `/help`) remain unimplemented and are +still listed as the remainder in `web/PARITY.md`. + +## Behaviour + +- A draft whose first word starts with `/` opens the recorded palette above the + composer. Rows are filtered case-insensitively by name prefix and show + `/name` plus the recorded summary (Material `ListTile`, Cupertino button on a + popup surface; no fixed row height). +- Up/Down wrap the highlight, and the highlight resets to the first row when the + filtered list shrinks (web `refreshComposerControls`). Enter or a tap + completes the highlighted command into the draft. +- Escape closes the palette until the draft is edited; editing to the same text + reopens it because the closure follows the edit, not the text. +- No slash draft reaches the prompt path. Enter, Ctrl/Cmd+Enter and the primary + control all take the command path: + - an unknown word consumes the draft and shows the web report + `“{word}” is not a command, so nothing was sent to the agent. Send it as a + message, or cancel.` with native `Send as message` / `Cancel` controls. + Only `Send as message` posts the exact trimmed draft. + - a recorded command keeps its draft and reports + `“/name” is not available yet, so nothing was sent to the agent.` until the + command actions land. + +## Checks + +- `flutter test test/features/chat` → 311 passed. +- `flutter analyze` → No issues found. +- `flutter build web --release` → ✓ Built build/web. +- `dart format --output=none --set-exit-if-changed` on the touched files → clean. +- `git diff --check` → clean. + +Not tested: rendered browser interaction/captures (belongs to the UI review +stage), Android/iOS builds or devices, live production chats. + +## Paths + +- `lib/features/chat/domain/chat_commands.dart` +- `lib/features/chat/conversation/chat_command_palette.dart` +- `lib/features/chat/conversation/chat_composer_bar.dart` +- `test/features/chat/domain/chat_commands_test.dart` +- `test/features/chat/conversation/chat_command_palette_test.dart` diff --git a/app/test/features/chat/conversation/chat_command_palette_test.dart b/app/test/features/chat/conversation/chat_command_palette_test.dart new file mode 100644 index 00000000..f4b31612 --- /dev/null +++ b/app/test/features/chat/conversation/chat_command_palette_test.dart @@ -0,0 +1,414 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_composer_bar_fixtures.dart'; + +void main() { + late ComposerBarGateway gateway; + late int sequence; + + String nextOperation() => 'op/${++sequence}'; + + setUp(() { + gateway = ComposerBarGateway()..page = fixtureTurn(); + sequence = 0; + }); + + tearDown(() => gateway.close()); + + Future<void> pumpComposer( + WidgetTester tester, { + bool cupertino = false, + }) async { + await tester.pumpWidget( + composerThread( + gateway, + cupertino: cupertino, + newOperationId: nextOperation, + ), + ); + await tester.pumpAndSettle(); + } + + Finder palette() => find.byKey(const Key('chat-command-palette')); + Finder row(String name) => find.byKey(ValueKey<String>('chat-command-$name')); + + testWidgets('a leading slash opens the filtered recorded command palette', ( + tester, + ) async { + await pumpComposer(tester); + + await tester.enterText(find.byKey(const Key('chat-composer-field')), '/'); + await tester.pump(); + + expect(palette(), findsOneWidget); + for (final name in ['new', 'close', 'rename', 'stop', 'help']) { + expect(row(name), findsOneWidget); + } + expect(find.text('/new'), findsOneWidget); + expect( + find.text('Start a fresh session in this directory'), + findsOneWidget, + ); + + await tester.enterText(find.byKey(const Key('chat-composer-field')), '/cl'); + await tester.pump(); + + expect(row('close'), findsOneWidget); + expect(row('new'), findsNothing); + expect(row('rename'), findsNothing); + expect(row('stop'), findsNothing); + expect(row('help'), findsNothing); + + // Recognition is case-insensitive, and an argument or plain text hides it. + await tester.enterText(find.byKey(const Key('chat-composer-field')), '/CL'); + await tester.pump(); + expect(row('close'), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-composer-field')), + '/close now', + ); + await tester.pump(); + expect(palette(), findsNothing); + + await tester.enterText( + find.byKey(const Key('chat-composer-field')), + 'plain text', + ); + await tester.pump(); + expect(palette(), findsNothing); + }); + + testWidgets('Escape closes the palette until the draft is edited again', ( + tester, + ) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/he'); + await tester.pump(); + expect(palette(), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + + expect(palette(), findsNothing); + expect(fieldText(tester), '/he'); + expect(gateway.promptBodies, isEmpty); + + await tester.enterText(field, '/hel'); + await tester.pump(); + expect(palette(), findsOneWidget); + + // Editing reopens even when the operator returns to the exact word that + // was dismissed: the closure follows the edit, not the text. + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + await tester.enterText(field, '/h'); + await tester.pump(); + expect(palette(), findsOneWidget); + await tester.enterText(field, '/he'); + await tester.pump(); + expect(palette(), findsOneWidget); + }); + + testWidgets('an unknown command reports locally and never prompts', ( + tester, + ) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/nope'); + await tester.pump(); + expect(palette(), findsNothing); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(gateway.promptBodies, isEmpty); + expect(fieldText(tester), ''); + expect( + find.text( + '“/nope” is not a command, so nothing was sent to the agent. ' + 'Send it as a message, or cancel.', + ), + findsOneWidget, + ); + expect(find.text('Send as message'), findsOneWidget); + expect(find.text('Cancel'), findsOneWidget); + + // The primary Send control takes the same command path, never the prompt. + await tester.enterText(field, '/also unknown'); + await tester.pump(); + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await tester.pumpAndSettle(); + + expect(gateway.promptBodies, isEmpty); + expect(fieldText(tester), ''); + expect( + find.text( + '“/also” is not a command, so nothing was sent to the agent. ' + 'Send it as a message, or cancel.', + ), + findsOneWidget, + ); + + await tester.tap(find.byKey(const Key('chat-command-cancel'))); + await tester.pump(); + + expect(find.byKey(const Key('chat-composer-command-notice')), findsNothing); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets('Send as message is the only route an unknown command takes', ( + tester, + ) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/nope'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(gateway.promptBodies, isEmpty); + + await tester.tap(find.byKey(const Key('chat-command-send-as-message'))); + await tester.pumpAndSettle(); + + expect(gateway.promptBodies.single['text'], '/nope'); + expect(fieldText(tester), ''); + expect(find.byKey(const Key('chat-composer-command-notice')), findsNothing); + }); + + testWidgets('a completed command never becomes a prompt', (tester) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/cl'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(fieldText(tester), '/close'); + expect(palette(), findsNothing); + expect(gateway.promptBodies, isEmpty); + + // A second Enter re-reports the command instead of sending it. + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(gateway.promptBodies, isEmpty); + expect(fieldText(tester), '/close'); + expect( + find.text( + '“/close” is not available yet, so nothing was sent to the agent.', + ), + findsOneWidget, + ); + + // The primary control and the explicit send shortcut take the same path. + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await tester.pumpAndSettle(); + expect(gateway.promptBodies, isEmpty); + expect(fieldText(tester), '/close'); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + + expect(gateway.promptBodies, isEmpty); + expect(fieldText(tester), '/close'); + + // An argument does not make the slash draft sendable either. + await tester.enterText(field, '/close now'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(gateway.promptBodies, isEmpty); + expect(fieldText(tester), '/close now'); + }); + + testWidgets('a command picked from the palette is never sent either', ( + tester, + ) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/h'); + await tester.pump(); + await tester.tap(row('help')); + await tester.pumpAndSettle(); + expect(fieldText(tester), '/help'); + + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await tester.pumpAndSettle(); + + expect(gateway.promptBodies, isEmpty); + expect(fieldText(tester), '/help'); + expect( + find.text( + '“/help” is not available yet, so nothing was sent to the agent.', + ), + findsOneWidget, + ); + }); + + testWidgets('a row completes the command and never prompts', (tester) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/cl'); + await tester.pump(); + await tester.tap(row('close')); + await tester.pumpAndSettle(); + + expect(fieldText(tester), '/close'); + expect(palette(), findsNothing); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets('Up/Down move the highlight and Enter completes it', ( + tester, + ) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/'); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(fieldText(tester), '/close'); + expect(palette(), findsNothing); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets('ArrowUp wraps the highlight to the last command', ( + tester, + ) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/'); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(fieldText(tester), '/help'); + expect(palette(), findsNothing); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets('the highlight resets when the filtered list shrinks', ( + tester, + ) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + // `/r` leaves one row, so the stale third index drops back to the first; + // widening to `/` must not restore it. + await tester.enterText(field, '/r'); + await tester.pump(); + await tester.enterText(field, '/'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(fieldText(tester), '/new'); + expect(palette(), findsNothing); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets( + 'the Cupertino host reports an unknown command with its controls', + (tester) async { + await pumpComposer(tester, cupertino: true); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/nope'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(gateway.promptBodies, isEmpty); + + await tester.tap(find.byKey(const Key('chat-command-send-as-message'))); + await tester.pumpAndSettle(); + + expect(gateway.promptBodies.single['text'], '/nope'); + expect(fieldText(tester), ''); + }, + ); + + testWidgets('Escape dismisses the local command report', (tester) async { + await pumpComposer(tester); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/nope'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('chat-composer-command-notice')), + findsOneWidget, + ); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + + expect(find.byKey(const Key('chat-composer-command-notice')), findsNothing); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets('the Cupertino host shows the same palette', (tester) async { + await pumpComposer(tester, cupertino: true); + final field = find.byKey(const Key('chat-composer-field')); + + await tester.enterText(field, '/re'); + await tester.pump(); + + expect(palette(), findsOneWidget); + expect(row('rename'), findsOneWidget); + expect(find.text('/rename'), findsOneWidget); + expect(find.text('Rename this session on this device'), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(palette(), findsNothing); + }); + + testWidgets('the palette fits a 320px phone at 2x text', (tester) async { + tester.view.physicalSize = const Size(640, 1200); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + await pumpComposer(tester, cupertino: true); + await tester.enterText(find.byKey(const Key('chat-composer-field')), '/'); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(palette(), findsOneWidget); + expect(row('new'), findsOneWidget); + expect(row('help'), findsOneWidget); + }); +} diff --git a/app/test/features/chat/domain/chat_commands_test.dart b/app/test/features/chat/domain/chat_commands_test.dart new file mode 100644 index 00000000..59ae91d7 --- /dev/null +++ b/app/test/features/chat/domain/chat_commands_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_commands.dart'; + +void main() { + test('records the web command list verbatim and in order', () { + expect(chatCommands.map((command) => command.name), [ + 'new', + 'close', + 'rename', + 'stop', + 'help', + ]); + expect(chatCommands.map((command) => command.usage), [ + '/new', + '/close', + '/rename <title>', + '/stop', + '/help', + ]); + expect(chatCommands.map((command) => command.summary), [ + 'Start a fresh session in this directory', + 'Finish this session for every client, keeping its history', + 'Rename this session on this device', + 'Stop the turn that is running', + 'List every command', + ]); + expect( + chatCommands.where((command) => command.takesArgument).map((c) => c.name), + ['rename'], + ); + }); + + test('a bare slash offers every recorded command', () { + expect(chatCommandSuggestions('/'), chatCommands); + expect(chatCommandSuggestions(' /'), chatCommands); + }); + + test('the name prefix filters case-insensitively', () { + expect(chatCommandSuggestions('/n').map((command) => command.name), [ + 'new', + ]); + expect(chatCommandSuggestions('/re').map((command) => command.name), [ + 'rename', + ]); + expect(chatCommandSuggestions('/CL').map((command) => command.name), [ + 'close', + ]); + expect(chatCommandSuggestions('/s').map((command) => command.name), [ + 'stop', + ]); + }); + + test('an argument, plain text or an unknown word offers nothing', () { + expect(chatCommandSuggestions('/close '), isEmpty); + expect(chatCommandSuggestions('/rename My chat'), isEmpty); + expect(chatCommandSuggestions('/zzz'), isEmpty); + expect(chatCommandSuggestions('hello'), isEmpty); + expect(chatCommandSuggestions(''), isEmpty); + }); + + test('the query is only the single slash word', () { + expect(chatCommandQuery('/Help'), 'help'); + expect(chatCommandQuery(' /He'), 'he'); + expect(chatCommandQuery('/help '), isNull); + expect(chatCommandQuery('help'), isNull); + }); + + test('the slash word carries any argument and is null without a slash', () { + expect(chatCommandWord('/close'), '/close'); + expect(chatCommandWord(' /close now'), '/close'); + expect(chatCommandWord('/rename My chat'), '/rename'); + expect(chatCommandWord('plain'), isNull); + expect(chatCommandWord('/'), '/'); + expect(chatCommandNamed('/CLOSE'), chatCommands[1]); + expect(chatCommandNamed('/close'), chatCommands[1]); + expect(chatCommandNamed('/rename My chat'), chatCommands[2]); + expect(chatCommandNamed('/zzz'), isNull); + expect(chatCommandNamed('/close now'), chatCommands[1]); + expect(chatCommandNamed('plain'), isNull); + }); + + test('the parsed reports keep the web client words', () { + expect( + chatUnknownCommandReport('/nope'), + '“/nope” is not a command, so nothing was sent to the agent. ' + 'Send it as a message, or cancel.', + ); + expect( + chatCommandUnavailableReport('/close'), + '“/close” is not available yet, so nothing was sent to the agent.', + ); + }); +}