diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 45524c5a..f420be58 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -32,6 +32,8 @@ import 'composer_focus_request.dart'; import 'composer_focus_restore.dart'; import 'composer_focus_ring.dart'; import '../ui/sessions/chat_color_palette.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'; @@ -74,6 +76,9 @@ double chatComposerBottomMargin([TargetPlatform? platform]) => 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'; @@ -122,6 +127,7 @@ class ChatComposerBar extends StatefulWidget { this.paste, this.pasteTarget = true, this.backgroundTasks, + this.runShell, this.placeholder = chatComposerPlaceholder, this.enterSends, this.images, @@ -161,6 +167,11 @@ class ChatComposerBar extends StatefulWidget { final bool pasteTarget; 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 Function(String command)? runShell; + @override State createState() => _ChatComposerBarState(); } @@ -206,6 +217,9 @@ class _ChatComposerBarState extends State { 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; @@ -487,6 +501,10 @@ class _ChatComposerBarState extends State { _completeCommand(commands[_selectedCommand % commands.length]); return; } + if (chatDraftIsShell(widget.composer.draft)) { + unawaited(_runShellDraft()); + return; + } if (chatCommandWord(widget.composer.draft) != null) { _runSlashDraft(); return; @@ -494,6 +512,38 @@ class _ChatComposerBarState extends State { 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 _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; @@ -767,6 +817,8 @@ class _ChatComposerBarState extends State { // inside the glass with the field, as one floating composer; only the // command palette, a separate menu, floats above it. final extras = [ + if (chatDraftIsShell(composer.draft)) + ChatShellModeIndicator(cupertino: cupertino), if (!_attachments.isEmpty) _attachmentStrip(context, cupertino), if (_uploading) _notice( @@ -1261,7 +1313,10 @@ class _ChatComposerBarState extends State { final composer = widget.composer; final enabled = stop ? !composer.stopping - : !_uploading && !composer.sending && composer.draft.trim().isNotEmpty; + : !_uploading && + !_shellStarting && + !composer.sending && + composer.draft.trim().isNotEmpty; void press() { if (stop) { unawaited(composer.stop()); @@ -1270,6 +1325,8 @@ class _ChatComposerBarState extends State { 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 { @@ -1279,7 +1336,11 @@ class _ChatComposerBarState extends State { // 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 : chatSendLabel; + final label = stop + ? chatStopLabel + : chatDraftIsShell(composer.draft) + ? chatRunShellLabel + : chatSendLabel; final key = Key(stop ? 'chat-composer-stop' : 'chat-composer-primary'); if (cupertino) { return Semantics( diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 0836adfe..8d8bf33e 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -57,6 +57,11 @@ import 'chat_transcript_cache.dart'; import '../files/files_controller.dart'; import '../files/files_panel.dart'; import '../files/files_preferences.dart'; +import '../shell/chat_shell_command.dart'; +import '../shell/chat_shell_run.dart'; +import '../shell/chat_shell_run_card.dart'; +import '../shell/chat_shell_runs_controller.dart'; +import '../shell/chat_shell_thread_support.dart'; import 'chat_transcript_scroll_view.dart'; import 'chat_permission_card_model.dart'; import 'chat_permission_group.dart'; @@ -182,6 +187,11 @@ class ChatThreadView extends StatefulWidget { class _ChatThreadViewState extends State { late ChatThreadController _controller = _attach(); late ChatComposerController _composer = _attachComposer(); + + /// The operator's own shell commands in this chat (see `../shell/`). + late ChatShellRunsController _shellRuns = _attachShellRuns(); + ChatShellRunsController _attachShellRuns() => + ChatShellRunsController(widget.gateway, widget.sessionId); late ChatRowKeys _rowKeys = ChatRowKeys(); final _sentEntrances = ChatSentEntrances(); final _rowWidgets = ChatRowWidgets(); @@ -575,6 +585,8 @@ class _ChatThreadViewState extends State { } _controller.dispose(); _composer.dispose(); + _shellRuns.dispose(); + _shellRuns = _attachShellRuns(); _files.removeListener(_persistFilesPreferences); _files.dispose(); _files = _newFilesController()..addListener(_persistFilesPreferences); @@ -611,6 +623,7 @@ class _ChatThreadViewState extends State { // so no earlier dismissal survives and nothing recorded before the gap is // painted while the repair runs. _dismissals.clear(); + unawaited(_shellRuns.refresh()); _preGapMessages = _controller.messages; _reconnecting = true; final generation = ++_syncGeneration; @@ -648,6 +661,7 @@ class _ChatThreadViewState extends State { _scroll.dispose(); _composer.dispose(); _controller.dispose(); + _shellRuns.dispose(); _files.removeListener(_persistFilesPreferences); _files.dispose(); super.dispose(); @@ -963,6 +977,7 @@ class _ChatThreadViewState extends State { animation: Listenable.merge([ _controller.transcriptChanges, _composer.deliveries, + _shellRuns.membership, ]), builder: (context, _) { final cupertino = @@ -1014,10 +1029,11 @@ class _ChatThreadViewState extends State { ); final notices = _dismissals.visible(allNotices); final compactionNotice = _noticeOf(notices, ChatNoticeKind.compaction); - final rows = [ + // The operator's own shell commands sit among the turns by start time. + final rows = withChatShellRunRows([ for (final row in allRows) if (!_hiddenRunningCompaction(row)) row, - ]; + ], _shellRuns.runs); // Older pages prepend messages and a live frame can append one, so a // folded assistant turn's first message id is not a stable identity. // ChatRowKeys carries a turn's key forward while it still holds any of @@ -1066,6 +1082,7 @@ class _ChatThreadViewState extends State { ), chatColor: chatSessionColor(widget.session), pasteTarget: widget.pasteTarget, + runShell: _shellRuns.start, backgroundTasks: ChatBackgroundTasks( key: ValueKey('chat-background-tasks-${widget.sessionId}'), gateway: widget.gateway, @@ -1362,7 +1379,11 @@ class _ChatThreadViewState extends State { : CupertinoIcons.folder, ), ], - moreActions: [?widget.sidebarControl, ...widget.paneControls], + moreActions: [ + ?widget.sidebarControl, + ...widget.paneControls, + chatShellRunMenuAction(onPressed: _runShellFromMenu), + ], controls: [ if (hasModel) ChatModelControl( @@ -1389,6 +1410,15 @@ class _ChatThreadViewState extends State { onChanged: widget.onModeChanged, ); + void _runShellFromMenu() => unawaited( + runChatShellFromMenu( + context, + _shellRuns, + cupertino: chatControlsStyleOf(context) == ChatControlsStyle.cupertino, + showNotice: _showCommandNotice, + ), + ); + ChatNotice? _noticeOf(List notices, ChatNoticeKind kind) { for (final notice in notices) { if (notice.kind == kind) return notice; @@ -1440,6 +1470,12 @@ class _ChatThreadViewState extends State { return ChatAgentReportCard(row: row, textBuilder: chatMarkdownText); } if (kind == 'system_notice') return ChatSystemNoticeLine(row: row); + if (kind == chatShellRunRowKind) { + return ChatShellRunCard( + controller: _shellRuns, + runId: '${row['run_id']}', + ); + } if (kind == 'task_notices') return ChatTaskNoticesGroup(row: row); if (kind == 'questions') return ChatQuestionsRow(row: row); if (kind == 'permission' || kind == 'question') { diff --git a/app/lib/features/chat/domain/chat_commands.dart b/app/lib/features/chat/domain/chat_commands.dart index 8ea87288..14f4f508 100644 --- a/app/lib/features/chat/domain/chat_commands.dart +++ b/app/lib/features/chat/domain/chat_commands.dart @@ -1,3 +1,5 @@ +import '../shell/chat_shell_command.dart'; + /// 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 @@ -113,10 +115,12 @@ String chatCommandArgument(String draft) { return draft.trimLeft().substring(word.length).trim(); } -/// `/help`'s local listing, in the same order and wording as the palette. -String chatCommandHelpText() => chatCommands - .map((command) => '${command.usage} — ${command.summary}') - .join('\n'); +/// `/help`'s local listing, in the same order and wording as the palette, +/// then the `!` shell-command hint. +String chatCommandHelpText() => [ + for (final command in chatCommands) '${command.usage} — ${command.summary}', + chatShellHelpLine, +].join('\n'); /// 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 diff --git a/app/lib/features/chat/shell/chat_shell_card_actions.dart b/app/lib/features/chat/shell/chat_shell_card_actions.dart new file mode 100644 index 00000000..3d7571f1 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_card_actions.dart @@ -0,0 +1,176 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'chat_shell_run.dart'; +import 'chat_shell_runs_controller.dart'; + +const String chatShellStopLabel = 'Stop'; +const String chatShellStoppingLabel = 'Stopping…'; +const String chatShellCopyLabel = 'Copy output'; +const String chatShellCopiedLabel = 'Copied'; +const String chatShellShareLabel = 'Send to agent'; +const String chatShellSharingLabel = 'Sending…'; +const String chatShellSharedLabel = 'Sent to agent'; +const String chatShellExpandLabel = 'Expand'; +const String chatShellCollapseLabel = 'Collapse'; + +/// The card's host buttons: Stop while running; Copy output, Send to agent +/// once finished; Expand/Collapse for the output area. +class ChatShellCardActions extends StatefulWidget { + const ChatShellCardActions({ + super.key, + required this.run, + required this.controller, + required this.cupertino, + required this.expanded, + required this.onToggleExpanded, + }); + + final ChatShellRun run; + final ChatShellRunsController controller; + final bool cupertino; + final bool expanded; + final VoidCallback onToggleExpanded; + + @override + State createState() => _ChatShellCardActionsState(); +} + +class _ChatShellCardActionsState extends State { + bool _copied = false; + Timer? _reset; + + @override + void dispose() { + _reset?.cancel(); + super.dispose(); + } + + /// Copies everything the server kept, reading it first when this card + /// holds only the newest part. + Future _copy() async { + final full = await widget.controller.loadAll(widget.run.id); + if (full == null) return; + await Clipboard.setData(ClipboardData(text: full.output)); + if (!mounted) return; + setState(() => _copied = true); + _reset?.cancel(); + _reset = Timer(const Duration(seconds: 2), () { + if (mounted) setState(() => _copied = false); + }); + } + + @override + Widget build(BuildContext context) { + final run = widget.run; + final controller = widget.controller; + final share = controller.shareState(run.id); + final stopping = controller.stopping(run.id); + return Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + if (run.running) + _button( + key: const Key('chat-shell-run-stop'), + label: stopping ? chatShellStoppingLabel : chatShellStopLabel, + material: Icons.stop, + cupertino: CupertinoIcons.stop_fill, + destructive: true, + onPressed: stopping + ? null + : () => unawaited(controller.stop(run.id)), + ), + if (!run.running && run.outputBytes > 0) + _button( + key: const Key('chat-shell-run-copy'), + label: _copied ? chatShellCopiedLabel : chatShellCopyLabel, + material: _copied ? Icons.check : Icons.copy_outlined, + cupertino: _copied + ? CupertinoIcons.checkmark + : CupertinoIcons.doc_on_doc, + onPressed: () => unawaited(_copy()), + ), + if (!run.running) + _button( + key: const Key('chat-shell-run-share'), + label: switch (share) { + ChatShellShareState.idle => chatShellShareLabel, + ChatShellShareState.sending => chatShellSharingLabel, + ChatShellShareState.sent => chatShellSharedLabel, + }, + material: share == ChatShellShareState.sent + ? Icons.check + : Icons.send_outlined, + cupertino: share == ChatShellShareState.sent + ? CupertinoIcons.checkmark + : CupertinoIcons.paperplane, + onPressed: share == ChatShellShareState.idle + ? () => unawaited(controller.share(run.id)) + : null, + ), + if (run.output.isNotEmpty) + _button( + key: const Key('chat-shell-run-expand'), + label: widget.expanded + ? chatShellCollapseLabel + : chatShellExpandLabel, + material: widget.expanded ? Icons.unfold_less : Icons.unfold_more, + cupertino: widget.expanded + ? CupertinoIcons.chevron_up + : CupertinoIcons.chevron_down, + onPressed: widget.onToggleExpanded, + ), + ], + ); + } + + Widget _button({ + required Key key, + required String label, + required IconData material, + required IconData cupertino, + required VoidCallback? onPressed, + bool destructive = false, + }) { + if (widget.cupertino) { + final color = destructive + ? CupertinoColors.systemRed.resolveFrom(context) + : null; + return CupertinoButton( + key: key, + padding: const EdgeInsets.symmetric(horizontal: 8), + onPressed: onPressed, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(cupertino, color: onPressed == null ? null : color), + const SizedBox(width: 6), + Text( + label, + style: onPressed == null || color == null + ? null + : TextStyle(color: color), + ), + ], + ), + ); + } + final style = destructive + ? TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.error, + ) + : null; + return TextButton.icon( + key: key, + style: style, + onPressed: onPressed, + icon: Icon(material), + label: Text(label), + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_command.dart b/app/lib/features/chat/shell/chat_shell_command.dart new file mode 100644 index 00000000..a2b02800 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_command.dart @@ -0,0 +1,92 @@ +import '../../../core/api_gateway.dart'; +import '../domain/chat_transcript.dart'; +import 'chat_shell_run.dart'; + +/// The composer's shell prefix: a draft starting with it runs as a command in +/// the chat's directory instead of being sent to the agent. +const String chatShellPrefix = '!'; + +/// The `/help` line for shell mode. +const String chatShellHelpLine = + '! — Run a shell command in this chat’s folder; ' + 'the agent does not see it unless you send it'; + +/// Shell mode's visible label and its explanation beside the composer. +const String chatShellModeLabel = 'Shell'; +const String chatShellModeHint = + 'Runs in this chat’s folder on its machine. The agent does not see it.'; + +/// The chat actions menu entry and its dialog. +const String chatShellRunActionLabel = 'Run command…'; +const String chatShellRunDialogTitle = 'Run command'; +const String chatShellRunDialogConfirm = 'Run'; + +/// Whether [draft] is in shell mode: its first non-blank character is `!`. +bool chatDraftIsShell(String draft) => + draft.trimLeft().startsWith(chatShellPrefix); + +/// The command a shell-mode draft runs (trimmed, without the `!`), or null +/// when [draft] is not in shell mode. An empty string means only `!` was typed. +String? chatShellCommandOf(String draft) { + if (!chatDraftIsShell(draft)) return null; + return draft.trimLeft().substring(chatShellPrefix.length).trim(); +} + +/// [rows] with one card row per run, placed by start time among the rows +/// that carry a recorded time. Rows without a time (a just-sent message, the +/// pending reply) keep their place; runs newer than every timed row follow. +List withChatShellRunRows( + List rows, + List runs, +) { + if (runs.isEmpty) return rows; + final ordered = [...runs]..sort((a, b) => a.startedAt.compareTo(b.startedAt)); + final merged = []; + var next = 0; + for (final row in rows) { + final time = _rowTime(row); + while (time != null && + next < ordered.length && + ordered[next].startedAt < time) { + merged.add(ordered[next++].toRow()); + } + merged.add(row); + } + while (next < ordered.length) { + merged.add(ordered[next++].toRow()); + } + return merged; +} + +int? _rowTime(JsonMap row) { + final created = row['created_at']; + if (created is int && created > 0) return created; + final message = row['message']; + if (message is Map) { + return chatMessageCreatedAt(Map.from(message)); + } + return null; +} + +/// The finished card's status words. +String chatShellStatusLabel(ChatShellRun run) => switch (run.state) { + ChatShellRunState.running => 'Running', + ChatShellRunState.succeeded => 'Exit 0', + ChatShellRunState.stopped => 'Stopped', + ChatShellRunState.interrupted => 'Interrupted', + ChatShellRunState.failed => + run.signal.isNotEmpty + ? 'Killed (${run.signal})' + : run.exitCode != null + ? 'Exit ${run.exitCode}' + : 'Failed', +}; + +/// How long the command ran, as the status chip's tail. +String chatShellDuration(int milliseconds) { + if (milliseconds < 1000) return '$milliseconds ms'; + final seconds = milliseconds / 1000; + if (seconds < 60) return '${seconds.toStringAsFixed(1)} s'; + final minutes = seconds ~/ 60; + return '${minutes}m ${(seconds % 60).round()}s'; +} diff --git a/app/lib/features/chat/shell/chat_shell_metrics.dart b/app/lib/features/chat/shell/chat_shell_metrics.dart new file mode 100644 index 00000000..f1232372 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_metrics.dart @@ -0,0 +1,32 @@ +import 'package:flutter/widgets.dart'; + +/// The one layout bound of a shell command card: how tall its output area +/// may grow. Collapsed it shows about [kChatShellOutputCollapsedLines] lines +/// of the host's (scaled) monospace text; expanded it may take +/// [kChatShellOutputExpandedShare] of the window height. Everything else in +/// the card is content-sized. +const int kChatShellOutputCollapsedLines = 12; +const double kChatShellOutputExpandedShare = 0.6; + +/// The monospace line height factor the output text is set at. +const double kChatShellOutputLineHeight = 1.35; + +/// Characters of output drawn at once. A command can print far more than a +/// text layout should carry; the card says when it shows only the newest +/// part, and Copy output still copies everything the server kept. +const int kChatShellRenderedOutputLimit = 64 * 1024; + +/// The output area's maximum height for this window, text scale and font. +double chatShellOutputMaxHeight( + BuildContext context, { + required double fontSize, + required bool expanded, +}) { + if (expanded) { + return MediaQuery.sizeOf(context).height * kChatShellOutputExpandedShare; + } + final line = + MediaQuery.textScalerOf(context).scale(fontSize) * + kChatShellOutputLineHeight; + return line * kChatShellOutputCollapsedLines; +} diff --git a/app/lib/features/chat/shell/chat_shell_mode_indicator.dart b/app/lib/features/chat/shell/chat_shell_mode_indicator.dart new file mode 100644 index 00000000..24e15755 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_mode_indicator.dart @@ -0,0 +1,60 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../conversation/chat_card_styles.dart'; +import 'chat_shell_command.dart'; + +/// Shown inside the composer while its draft starts with `!`: the draft is a +/// shell command for this chat's folder, not a message to the agent. +class ChatShellModeIndicator extends StatelessWidget { + const ChatShellModeIndicator({super.key, required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) { + final accent = cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary; + final label = (chatCardBodyStyle(context, cupertino) ?? const TextStyle()) + .copyWith(color: accent, fontWeight: FontWeight.w600); + return Semantics( + key: const Key('chat-composer-shell-mode'), + container: true, + liveRegion: true, + label: '$chatShellModeLabel mode. $chatShellModeHint', + child: ExcludeSemantics( + child: Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Wrap( + spacing: 8, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + cupertino + ? CupertinoIcons.chevron_left_slash_chevron_right + : Icons.terminal, + color: accent, + size: MediaQuery.textScalerOf( + context, + ).scale(label.fontSize ?? 14), + ), + const SizedBox(width: 4), + Text(chatShellModeLabel, style: label), + ], + ), + Text( + chatShellModeHint, + style: chatCardSecondaryStyle(context, cupertino), + ), + ], + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_output_view.dart b/app/lib/features/chat/shell/chat_shell_output_view.dart new file mode 100644 index 00000000..f7b1d354 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_output_view.dart @@ -0,0 +1,117 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/text/monospace.dart'; +import '../conversation/chat_card_styles.dart'; +import 'chat_shell_metrics.dart'; +import 'chat_shell_run.dart'; + +/// The terminal-style output area of one command card: the host's monospace +/// body on a quiet inset surface, scrollable inside a bounded height and +/// anchored at the newest line while the command runs. +class ChatShellOutputView extends StatefulWidget { + const ChatShellOutputView({ + super.key, + required this.run, + required this.cupertino, + required this.expanded, + }); + + final ChatShellRun run; + final bool cupertino; + final bool expanded; + + @override + State createState() => _ChatShellOutputViewState(); +} + +class _ChatShellOutputViewState extends State { + final ScrollController _scroll = ScrollController(); + + @override + void dispose() { + _scroll.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final run = widget.run; + final cupertino = widget.cupertino; + final body = chatCardBodyStyle(context, cupertino) ?? const TextStyle(); + final fontSize = (body.fontSize ?? 14) * 0.95; + final style = body.copyWith( + fontFamily: appMonospaceFamily, + fontSize: fontSize, + height: kChatShellOutputLineHeight, + ); + final secondary = chatCardSecondaryStyle(context, cupertino); + var text = run.output; + final clipped = text.length > kChatShellRenderedOutputLimit; + if (clipped) { + text = text.substring(text.length - kChatShellRenderedOutputLimit); + } + final notes = [ + if (run.truncated) 'Earlier output was dropped.', + if (clipped) + 'Showing only the newest part; Copy output copies all of it.', + ]; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (notes.isNotEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + notes.join(' '), + key: const Key('chat-shell-output-truncated'), + style: secondary, + ), + ), + DecoratedBox( + decoration: BoxDecoration( + color: chatCardFillColor(context, cupertino), + borderRadius: BorderRadius.circular(8), + ), + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: chatShellOutputMaxHeight( + context, + fontSize: fontSize, + expanded: widget.expanded, + ), + ), + child: _scrollable( + Padding( + padding: const EdgeInsets.all(10), + child: text.isEmpty + ? Text( + run.running ? 'No output yet.' : 'No output.', + style: secondary, + ) + : Text( + text, + key: const Key('chat-shell-output-text'), + style: style, + ), + ), + ), + ), + ), + ], + ); + } + + /// A short output sizes the box to itself; a long one scrolls inside it, + /// starting from (and following) the newest line. + Widget _scrollable(Widget child) { + final scroll = SingleChildScrollView( + controller: _scroll, + reverse: true, + child: SizedBox(width: double.infinity, child: child), + ); + return widget.cupertino + ? CupertinoScrollbar(controller: _scroll, child: scroll) + : Scrollbar(controller: _scroll, child: scroll); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_run.dart b/app/lib/features/chat/shell/chat_shell_run.dart new file mode 100644 index 00000000..37ff8917 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_run.dart @@ -0,0 +1,161 @@ +import '../../../core/api_gateway.dart'; + +/// How an operator shell command stands, as the card shows it. +enum ChatShellRunState { running, succeeded, failed, stopped, interrupted } + +/// Characters of live output one card keeps; older text is dropped (and said +/// to be) so a flooding command cannot grow the transcript without bound. The +/// server keeps its own 1 MiB tail, which Copy output and Load all read. +const int chatShellLiveOutputLimit = 256 * 1024; + +/// One command the operator ran in this chat (`chat_shell_run`), as recorded +/// by the server: never part of the agent's transcript. +class ChatShellRun { + const ChatShellRun({ + required this.id, + required this.command, + required this.directory, + required this.status, + required this.startedAt, + this.exitCode, + this.signal = '', + this.error = '', + this.endedAt = 0, + this.durationMs = 0, + this.output = '', + this.outputStart = 0, + this.outputEnd = 0, + this.outputBytes = 0, + this.gap = false, + }); + + final String id; + final String command; + final String directory; + + /// The server's status word: running, exited, stopped, failed, interrupted. + final String status; + final int startedAt; + final int? exitCode; + final String signal; + final String error; + final int endedAt; + final int durationMs; + + /// The text held here, covering absolute output bytes from [outputStart] + /// to [outputEnd] (0 when unknown, for a readback). + final String output; + final int outputStart; + final int outputEnd; + final int outputBytes; + + /// True when live frames were missed, so [output] is not one contiguous + /// stretch of what the command wrote. + final bool gap; + + /// Whether earlier output is not shown here. + bool get truncated => outputStart > 0 || gap; + + ChatShellRunState get state => switch (status) { + 'running' => ChatShellRunState.running, + 'stopped' => ChatShellRunState.stopped, + 'interrupted' => ChatShellRunState.interrupted, + 'exited' when exitCode == 0 && signal.isEmpty => + ChatShellRunState.succeeded, + _ => ChatShellRunState.failed, + }; + + bool get running => state == ChatShellRunState.running; + + static ChatShellRun? fromJson(Object? value) { + if (value is! Map) return null; + final id = '${value['id'] ?? ''}'.trim(); + if (id.isEmpty) return null; + final output = '${value['output'] ?? ''}'; + final start = _int(value['output_start']); + final bytes = _int(value['output_bytes']); + return ChatShellRun( + id: id, + command: '${value['command'] ?? ''}', + directory: '${value['directory'] ?? ''}', + status: '${value['status'] ?? ''}', + startedAt: _int(value['started_at']), + exitCode: value['exit_code'] is num + ? (value['exit_code'] as num).toInt() + : null, + signal: '${value['signal'] ?? ''}', + error: '${value['error'] ?? ''}', + endedAt: _int(value['ended_at']), + durationMs: _int(value['duration_ms']), + output: output, + outputStart: start, + // A readback's text runs to the newest byte the server had. + outputEnd: output.isEmpty && start == 0 ? 0 : bytes, + outputBytes: bytes, + ); + } + + /// This run with a lifecycle frame's facts; the held output stays. + ChatShellRun withLifecycle(ChatShellRun next) => ChatShellRun( + id: id, + command: next.command.isEmpty ? command : next.command, + directory: next.directory.isEmpty ? directory : next.directory, + status: next.status, + startedAt: next.startedAt == 0 ? startedAt : next.startedAt, + exitCode: next.exitCode, + signal: next.signal, + error: next.error, + endedAt: next.endedAt, + durationMs: next.durationMs, + output: output, + outputStart: outputStart, + outputEnd: outputEnd, + outputBytes: next.outputBytes > outputBytes + ? next.outputBytes + : outputBytes, + gap: gap, + ); + + /// This run with one live output chunk covering bytes [offset, end). A + /// chunk this copy already holds is ignored; one after a hole starts a new + /// stretch and marks the gap rather than joining unrelated text. + ChatShellRun withChunk(String text, int offset, int end) { + if (end <= outputEnd) return this; + final contiguous = offset == outputEnd; + var joined = contiguous ? output + text : text; + var dropped = !contiguous && outputEnd > 0; + if (joined.length > chatShellLiveOutputLimit) { + joined = joined.substring(joined.length - chatShellLiveOutputLimit); + dropped = true; + } + return ChatShellRun( + id: id, + command: command, + directory: directory, + status: status, + startedAt: startedAt, + exitCode: exitCode, + signal: signal, + error: error, + endedAt: endedAt, + durationMs: durationMs, + output: joined, + outputStart: contiguous ? outputStart : offset, + outputEnd: end, + outputBytes: end > outputBytes ? end : outputBytes, + gap: gap || dropped || (!contiguous && offset > 0), + ); + } + + JsonMap toRow() => { + 'kind': chatShellRunRowKind, + 'key': 'chat-shell-run-$id', + 'run_id': id, + 'created_at': startedAt, + }; +} + +/// The transcript row kind of one operator command card. +const String chatShellRunRowKind = 'shell_run'; + +int _int(Object? value) => value is num ? value.toInt() : 0; diff --git a/app/lib/features/chat/shell/chat_shell_run_card.dart b/app/lib/features/chat/shell/chat_shell_run_card.dart new file mode 100644 index 00000000..628dfd2b --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_run_card.dart @@ -0,0 +1,149 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/text/monospace.dart'; +import '../../../ui/theme/app_theme.dart'; +import '../conversation/chat_card_styles.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'chat_shell_card_actions.dart'; +import 'chat_shell_output_view.dart'; +import 'chat_shell_run.dart'; +import 'chat_shell_runs_controller.dart'; +import 'chat_shell_status.dart'; + +/// One operator command in the transcript, as a terminal-style card in the +/// reading column: the command and folder, its live output, a spinner and +/// Stop while it runs, then its exit status, Copy output and Send to agent. +/// +/// It listens to [controller] itself, so streamed output rebuilds only this +/// card, never the transcript. +class ChatShellRunCard extends StatefulWidget { + const ChatShellRunCard({ + super.key, + required this.controller, + required this.runId, + }); + + final ChatShellRunsController controller; + final String runId; + + @override + State createState() => _ChatShellRunCardState(); +} + +class _ChatShellRunCardState extends State { + bool _expanded = false; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + return ListenableBuilder( + listenable: widget.controller, + builder: (context, _) { + final run = widget.controller.run(widget.runId); + if (run == null) return const SizedBox.shrink(); + final body = _body(context, run, cupertino); + return Semantics( + identifier: 'chat-shell-run-card', + container: true, + child: cupertino + ? CupertinoListSection.insetGrouped( + backgroundColor: AppColors.groupedBackground, + margin: const EdgeInsets.only(bottom: 12), + children: [ + Padding(padding: const EdgeInsets.all(16), child: body), + ], + ) + : Card( + margin: const EdgeInsets.only(bottom: 12), + child: Padding( + padding: const EdgeInsets.all(16), + child: body, + ), + ), + ); + }, + ); + } + + Widget _body(BuildContext context, ChatShellRun run, bool cupertino) { + final controller = widget.controller; + final error = controller.errorFor(run.id); + final command = (chatCardBodyStyle(context, cupertino) ?? const TextStyle()) + .copyWith(fontFamily: appMonospaceFamily, fontWeight: FontWeight.w600); + return Column( + key: ValueKey('chat-shell-run-${run.id}'), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsetsDirectional.only(end: 12), + child: Icon( + cupertino + ? CupertinoIcons.chevron_left_slash_chevron_right + : Icons.terminal, + color: chatCardSecondaryColor(context, cupertino), + ), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '\$ ${run.command}', + key: const Key('chat-shell-run-command'), + style: command, + ), + if (run.directory.isNotEmpty) + Text( + run.directory, + style: chatCardSecondaryStyle(context, cupertino), + ), + ], + ), + ), + const SizedBox(width: 8), + ChatShellStatus(run: run, cupertino: cupertino), + ], + ), + const SizedBox(height: 12), + ChatShellOutputView( + run: run, + cupertino: cupertino, + expanded: _expanded, + ), + if (run.error.isNotEmpty && !run.running) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + run.error, + style: chatCardSecondaryStyle(context, cupertino), + ), + ), + const SizedBox(height: 4), + ChatShellCardActions( + run: run, + controller: controller, + cupertino: cupertino, + expanded: _expanded, + onToggleExpanded: () => setState(() => _expanded = !_expanded), + ), + if (error != null) + Semantics( + liveRegion: true, + child: Text( + error, + key: const Key('chat-shell-run-error'), + style: + (chatCardBodyStyle(context, cupertino) ?? const TextStyle()) + .copyWith(color: chatCardErrorColor(context, cupertino)), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_run_dialog.dart b/app/lib/features/chat/shell/chat_shell_run_dialog.dart new file mode 100644 index 00000000..ba50f30a --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_run_dialog.dart @@ -0,0 +1,113 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/text/monospace.dart'; +import 'chat_shell_command.dart'; + +/// The chat actions menu's "Run command…": a small host dialog with one +/// command field. Returns the trimmed command, or null when cancelled. +Future showChatShellRunDialog( + BuildContext context, { + required bool cupertino, +}) => cupertino + ? showCupertinoDialog( + context: context, + barrierDismissible: true, + builder: (_) => const ChatShellRunDialog(cupertino: true), + ) + : showDialog( + context: context, + builder: (_) => const ChatShellRunDialog(cupertino: false), + ); + +class ChatShellRunDialog extends StatefulWidget { + const ChatShellRunDialog({super.key, required this.cupertino}); + + final bool cupertino; + + @override + State createState() => _ChatShellRunDialogState(); +} + +class _ChatShellRunDialogState extends State { + final TextEditingController _text = TextEditingController(); + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + void _submit() { + final command = _text.text.trim(); + Navigator.pop(context, command.isEmpty ? null : command); + } + + void _cancel() => Navigator.pop(context); + + @override + Widget build(BuildContext context) { + const mono = TextStyle(fontFamily: appMonospaceFamily); + if (widget.cupertino) { + return CupertinoAlertDialog( + title: const Text(chatShellRunDialogTitle), + content: Column( + children: [ + const Text(chatShellModeHint), + const SizedBox(height: 12), + CupertinoTextField( + key: const Key('chat-shell-run-field'), + controller: _text, + autofocus: true, + placeholder: 'Command', + style: mono, + onSubmitted: (_) => _submit(), + ), + ], + ), + actions: [ + CupertinoDialogAction( + onPressed: _cancel, + child: const Text('Cancel'), + ), + CupertinoDialogAction( + key: const Key('chat-shell-run-confirm'), + isDefaultAction: true, + onPressed: _submit, + child: const Text(chatShellRunDialogConfirm), + ), + ], + ); + } + return AlertDialog( + title: const Text(chatShellRunDialogTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text(chatShellModeHint), + const SizedBox(height: 12), + TextField( + key: const Key('chat-shell-run-field'), + controller: _text, + autofocus: true, + style: mono, + decoration: const InputDecoration( + labelText: 'Command', + prefixText: '\$ ', + ), + onSubmitted: (_) => _submit(), + ), + ], + ), + actions: [ + TextButton(onPressed: _cancel, child: const Text('Cancel')), + FilledButton( + key: const Key('chat-shell-run-confirm'), + onPressed: _submit, + child: const Text(chatShellRunDialogConfirm), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_runs_controller.dart b/app/lib/features/chat/shell/chat_shell_runs_controller.dart new file mode 100644 index 00000000..ba17a18d --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_runs_controller.dart @@ -0,0 +1,176 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../core/error_reason.dart'; +import 'chat_shell_run.dart'; +import 'chat_shell_runs_repository.dart'; + +/// Where one run's "Send to agent" stands. +enum ChatShellShareState { idle, sending, sent } + +/// One chat's operator shell commands: the recorded runs, their live output +/// from `chat_shell_run_event` frames, and the card actions. +/// +/// It notifies on every change (cards listen to it); [membership] notifies +/// only when the set of runs changes, so the transcript is not rebuilt for +/// every output chunk. +class ChatShellRunsController extends ChangeNotifier { + ChatShellRunsController(this.gateway, this.sessionId) + : _repository = ChatShellRunsRepository(gateway) { + _frames = gateway.frames.listen(_onFrame, onError: (_) {}); + unawaited(refresh()); + } + + final ApiGateway gateway; + final String sessionId; + final ChatShellRunsRepository _repository; + StreamSubscription? _frames; + final Map _runs = {}; + final ValueNotifier _membership = ValueNotifier(0); + final Set _stopping = {}; + final Map _shares = {}; + final Map _errors = {}; + bool _disposed = false; + int _generation = 0; + + Listenable get membership => _membership; + List get runs => List.unmodifiable(_runs.values); + ChatShellRun? run(String id) => _runs[id]; + bool stopping(String id) => _stopping.contains(id); + ChatShellShareState shareState(String id) => + _shares[id] ?? ChatShellShareState.idle; + + /// The last refused card action of [id], in the server's words. + String? errorFor(String id) => _errors[id]; + + /// Reads the recorded runs again (open, reconnect). Runs this copy holds + /// with newer output than the readback keep their own copy. + Future refresh() async { + final token = ++_generation; + try { + final listed = await _repository.runs(sessionId); + if (_disposed || token != _generation) return; + for (final run in listed) { + final held = _runs[run.id]; + _runs[run.id] = held != null && held.outputEnd > run.outputEnd + ? held.withLifecycle(run) + : run; + } + _changed(membership: true); + } catch (_) { + // An older server has no shell commands; the transcript is unchanged. + } + } + + /// Starts [command] in the chat's directory. Returns the refusal, or null. + Future start(String command) async { + try { + final run = await _repository.run(sessionId, command); + if (_disposed) return null; + _runs.putIfAbsent(run.id, () => run); + _changed(membership: true); + return null; + } catch (error) { + return _reason(error); + } + } + + Future stop(String id) async { + if (_stopping.contains(id)) return; + _stopping.add(id); + _errors.remove(id); + _changed(); + try { + await _repository.stop(sessionId, id); + } catch (error) { + _stopping.remove(id); + _errors[id] = _reason(error); + _changed(); + } + } + + /// Queues the run's command and output tail as an ordinary prompt. + Future share(String id) async { + if (shareState(id) == ChatShellShareState.sending) return; + _shares[id] = ChatShellShareState.sending; + _errors.remove(id); + _changed(); + try { + await _repository.share(sessionId, id); + _shares[id] = ChatShellShareState.sent; + } catch (error) { + _shares.remove(id); + _errors[id] = _reason(error); + } + _changed(); + } + + /// Every byte the server retained for [id]: what Copy output copies and + /// Show all draws. Null when it cannot be read (the error is recorded). + Future loadAll(String id) async { + final held = _runs[id]; + if (held == null) return null; + if (!held.truncated && !held.running) return held; + try { + final full = await _repository.output(sessionId, id); + if (_disposed) return null; + final latest = _runs[id] ?? held; + // A frame newer than the read keeps the card's own lifecycle facts. + final merged = full.withLifecycle(latest.running ? full : latest); + _runs[id] = merged; + _changed(); + return merged; + } catch (error) { + _errors[id] = _reason(error); + _changed(); + return null; + } + } + + void _onFrame(JsonMap envelope) { + if (_disposed || envelope['type'] != 'chat_shell_run_event') return; + final frame = envelope['chat_shell_run_event']; + if (frame is! Map || frame['session_id'] != sessionId) return; + final id = '${frame['run_id'] ?? ''}'; + final record = ChatShellRun.fromJson(frame['run']); + if (record != null) { + final held = _runs[record.id]; + _runs[record.id] = held == null ? record : held.withLifecycle(record); + if (!record.running) _stopping.remove(record.id); + _changed(membership: held == null); + return; + } + final held = _runs[id]; + if (held == null) { + // Output for a run this copy has not seen yet: read the record. + unawaited(refresh()); + return; + } + _runs[id] = held.withChunk( + '${frame['output'] ?? ''}', + (frame['offset'] as num?)?.toInt() ?? 0, + (frame['end'] as num?)?.toInt() ?? 0, + ); + _changed(); + } + + void _changed({bool membership = false}) { + if (_disposed) return; + if (membership) _membership.value++; + notifyListeners(); + } + + String _reason(Object error) => + describeErrorReason(error, fallback: 'The server did not answer.'); + + @override + void dispose() { + _disposed = true; + _generation++; + unawaited(_frames?.cancel()); + _membership.dispose(); + super.dispose(); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_runs_repository.dart b/app/lib/features/chat/shell/chat_shell_runs_repository.dart new file mode 100644 index 00000000..c355d173 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_runs_repository.dart @@ -0,0 +1,53 @@ +import '../../../core/api_gateway.dart'; +import 'chat_shell_run.dart'; + +/// Wire adapter for the server's operator shell commands. +class ChatShellRunsRepository { + const ChatShellRunsRepository(this.gateway); + final ApiGateway gateway; + + JsonMap _body(String sessionId, {String? command, String? runId}) => { + 'chat_shell_run_request': { + 'session_id': sessionId, + 'command': ?command, + 'run_id': ?runId, + }, + }; + + /// Starts [command]; the reply is its running record. + Future run(String sessionId, String command) async => _record( + await gateway.call('chat_shell_run', _body(sessionId, command: command)), + ); + + Future stop(String sessionId, String runId) => + gateway.call('chat_shell_stop', _body(sessionId, runId: runId)); + + /// The session's recorded runs, oldest first, each with its output tail. + Future> runs(String sessionId) async { + final reply = await gateway.call('chat_shell_runs', { + 'chat_query': {'session_id': sessionId}, + }); + final value = reply['chat_shell_runs']; + return [ + if (value is List) + for (final item in value) ?ChatShellRun.fromJson(item), + ]; + } + + /// One run with the whole output the server retained. + Future output(String sessionId, String runId) async => _record( + await gateway.call('chat_shell_run_output', _body(sessionId, runId: runId)), + ); + + /// Queues an ordinary prompt carrying the run for the agent. + Future share(String sessionId, String runId) => + gateway.call('chat_shell_share', _body(sessionId, runId: runId)); + + ChatShellRun _record(JsonMap reply) { + final run = ChatShellRun.fromJson(reply['chat_shell_run']); + if (run == null) { + throw const FormatException('The server did not return the command.'); + } + return run; + } +} diff --git a/app/lib/features/chat/shell/chat_shell_status.dart b/app/lib/features/chat/shell/chat_shell_status.dart new file mode 100644 index 00000000..201754f8 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_status.dart @@ -0,0 +1,74 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../conversation/chat_card_styles.dart'; +import 'chat_shell_command.dart'; +import 'chat_shell_run.dart'; + +/// A command's state at the card's top end: the host's activity indicator +/// while it runs, then a status chip (exit code, stopped, interrupted) with +/// how long it ran. The words carry the state; colour only repeats it. +class ChatShellStatus extends StatelessWidget { + const ChatShellStatus({ + super.key, + required this.run, + required this.cupertino, + }); + + final ChatShellRun run; + final bool cupertino; + + @override + Widget build(BuildContext context) { + if (run.running) { + return Semantics( + key: const Key('chat-shell-run-running'), + label: chatShellStatusLabel(run), + child: cupertino + ? const CupertinoActivityIndicator() + // As tall as the line of text beside it, at any text scale. + : SizedBox.square( + dimension: MediaQuery.textScalerOf(context).scale(20), + child: const CircularProgressIndicator(strokeWidth: 2), + ), + ); + } + final label = run.durationMs > 0 + ? '${chatShellStatusLabel(run)} · ${chatShellDuration(run.durationMs)}' + : chatShellStatusLabel(run); + final color = switch (run.state) { + ChatShellRunState.succeeded => + cupertino + ? CupertinoColors.systemGreen.resolveFrom(context) + : Theme.of(context).colorScheme.primary, + ChatShellRunState.failed => chatCardErrorColor(context, cupertino), + _ => chatCardSecondaryColor(context, cupertino), + }; + final icon = switch (run.state) { + ChatShellRunState.succeeded => + cupertino + ? CupertinoIcons.checkmark_circle + : Icons.check_circle_outline, + ChatShellRunState.failed => + cupertino ? CupertinoIcons.xmark_circle : Icons.error_outline, + _ => cupertino ? CupertinoIcons.stop_circle : Icons.stop_circle_outlined, + }; + if (cupertino) { + return Row( + key: const Key('chat-shell-run-status'), + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, color: color, size: 18), + const SizedBox(width: 4), + Text(label, style: chatCardSecondaryStyle(context, true)), + ], + ); + } + return Chip( + key: const Key('chat-shell-run-status'), + avatar: Icon(icon, color: color), + label: Text(label), + visualDensity: VisualDensity.compact, + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_thread_support.dart b/app/lib/features/chat/shell/chat_shell_thread_support.dart new file mode 100644 index 00000000..f9348053 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_thread_support.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/segmented_bar_overflow.dart'; +import 'chat_shell_command.dart'; +import 'chat_shell_run_dialog.dart'; +import 'chat_shell_runs_controller.dart'; + +/// The conversation's "Run command…" entry in its actions (More) menu. +Widget chatShellRunMenuAction({required VoidCallback onPressed}) => + SegmentedOverflowAction( + key: const ValueKey('chat-shell-run-action'), + overflowEntry: SegmentedOverflowEntry( + label: chatShellRunActionLabel, + icon: Icons.terminal, + onPressed: onPressed, + ), + child: const SizedBox.shrink(), + ); + +/// Asks for a command and starts it; a refusal becomes the conversation's +/// own failed notice. Nothing reaches the agent. +Future runChatShellFromMenu( + BuildContext context, + ChatShellRunsController controller, { + required bool cupertino, + required void Function(String text, {bool failed}) showNotice, +}) async { + final command = await showChatShellRunDialog(context, cupertino: cupertino); + if (command == null) return; + final refusal = await controller.start(command); + if (refusal != null) { + showNotice("Couldn't run the command: $refusal", failed: true); + } +} diff --git a/app/test/features/chat/conversation/chat_command_palette_test.dart b/app/test/features/chat/conversation/chat_command_palette_test.dart index 8cb4f376..5a276b70 100644 --- a/app/test/features/chat/conversation/chat_command_palette_test.dart +++ b/app/test/features/chat/conversation/chat_command_palette_test.dart @@ -256,7 +256,9 @@ void main() { '/close — Finish this session for every client, keeping its history\n' '/rename — Rename this session\n' '/stop — Stop the turn that is running\n' - '/help — List every command', + '/help — List every command\n' + '!<command> — Run a shell command in this chat’s folder; ' + 'the agent does not see it unless you send it', ), findsOneWidget, ); diff --git a/app/test/features/chat/shell/chat_shell_command_test.dart b/app/test/features/chat/shell/chat_shell_command_test.dart new file mode 100644 index 00000000..6a3b3221 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_command_test.dart @@ -0,0 +1,103 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_commands.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_command.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart'; + +ChatShellRun _run(String id, int started, {String status = 'running'}) => + ChatShellRun( + id: id, + command: 'ls', + directory: '/w', + status: status, + startedAt: started, + ); + +void main() { + test('a leading ! (after blanks) is shell mode and names the command', () { + expect(chatDraftIsShell('!ls -la'), isTrue); + expect(chatDraftIsShell(' ! git status'), isTrue); + expect(chatDraftIsShell('say !hi'), isFalse); + expect(chatDraftIsShell('/help'), isFalse); + expect(chatShellCommandOf(' ! git status '), 'git status'); + expect(chatShellCommandOf('!'), ''); + expect(chatShellCommandOf('hello'), isNull); + }); + + test('/help lists the shell hint after the commands', () { + expect(chatCommandHelpText().split('\n').last, chatShellHelpLine); + }); + + test('runs are placed among timed rows by start time', () { + final rows = [ + { + 'kind': 'user', + 'key': 'u1', + 'message': {'created_at': 100}, + }, + {'kind': 'assistant', 'key': 'a1', 'created_at': 200}, + {'kind': 'user', 'key': 'local', 'message': <String, dynamic>{}}, + {'kind': 'assistant', 'key': 'a2', 'created_at': 400}, + ]; + final merged = withChatShellRunRows(rows, [ + _run('late', 500), + _run('early', 150), + _run('mid', 300), + ]); + expect(merged.map((row) => row['key']), [ + 'u1', + 'chat-shell-run-early', + 'a1', + 'local', + 'chat-shell-run-mid', + 'a2', + 'chat-shell-run-late', + ]); + expect(withChatShellRunRows(rows, const []), same(rows)); + }); + + test('status words follow the recorded outcome', () { + ChatShellRun ended(String status, {int? code, String signal = ''}) => + ChatShellRun( + id: 'r', + command: 'x', + directory: '/', + status: status, + startedAt: 1, + exitCode: code, + signal: signal, + ); + expect(ended('exited', code: 0).state, ChatShellRunState.succeeded); + expect(chatShellStatusLabel(ended('exited', code: 2)), 'Exit 2'); + expect(ended('exited', code: 2).state, ChatShellRunState.failed); + expect( + chatShellStatusLabel(ended('exited', signal: 'killed')), + 'Killed (killed)', + ); + expect(chatShellStatusLabel(ended('stopped')), 'Stopped'); + expect(chatShellStatusLabel(ended('interrupted')), 'Interrupted'); + expect(chatShellDuration(250), '250 ms'); + expect(chatShellDuration(1500), '1.5 s'); + expect(chatShellDuration(125000), '2m 5s'); + }); + + test('live chunks join only when contiguous and mark a gap otherwise', () { + var run = _run('r', 1); + run = run.withChunk('abc', 0, 3).withChunk('def', 3, 6); + expect(run.output, 'abcdef'); + expect(run.truncated, isFalse); + expect(run.withChunk('abc', 0, 3).output, 'abcdef', reason: 'a repeat'); + final gapped = run.withChunk('xyz', 10, 13); + expect(gapped.output, 'xyz'); + expect(gapped.truncated, isTrue); + final read = ChatShellRun.fromJson({ + 'id': 'r', + 'status': 'exited', + 'exit_code': 0, + 'output': 'tail', + 'output_start': 6, + 'output_bytes': 10, + })!; + expect(read.truncated, isTrue); + expect(read.withChunk('more', 10, 14).output, 'tailmore'); + }); +} diff --git a/app/test/features/chat/shell/chat_shell_composer_test.dart b/app/test/features/chat/shell/chat_shell_composer_test.dart new file mode 100644 index 00000000..96dd6ccb --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_composer_test.dart @@ -0,0 +1,90 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart'; + +import 'chat_shell_fixtures.dart'; + +/// A desktop keyboard, where Enter sends. +final _desktop = TargetPlatformVariant.only(TargetPlatform.linux); + +void main() { + late ShellGateway gateway; + + setUp(() => gateway = ShellGateway()); + tearDown(() => gateway.close()); + + final field = find.byKey(const Key('chat-composer-field')); + final shellMode = find.byKey(const Key('chat-composer-shell-mode')); + + testWidgets('a leading ! shows Shell mode and runs instead of sending', ( + tester, + ) async { + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + + await tester.enterText(field, 'hello'); + await tester.pump(); + expect(shellMode, findsNothing); + await tester.enterText(field, '!git status'); + await tester.pump(); + expect(shellMode, findsOneWidget); + expect(find.text('Shell'), findsOneWidget); + expect(find.byTooltip('Run command'), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + await tester.pump(); + expect(gateway.bodies('chat_shell_run').single['command'], 'git status'); + expect(gateway.calls.where((c) => c.type == 'chat_prompt'), isEmpty); + expect(shellMode, findsNothing, reason: 'the draft was consumed'); + // The started run is drawn as a card at once. + expect(find.text('\$ git status'), findsOneWidget); + }, variant: _desktop); + + testWidgets('a refused command keeps the draft and says why', (tester) async { + gateway.refusal = 'this chat already runs 4 commands'; + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.enterText(field, '!sleep 9'); + await tester.pump(); + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await tester.pump(); + await tester.pump(); + expect(find.textContaining('already runs 4 commands'), findsOneWidget); + expect(shellMode, findsOneWidget); + expect(gateway.calls.where((c) => c.type == 'chat_prompt'), isEmpty); + }); + + testWidgets('a bare ! asks for a command and sends nothing', (tester) async { + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.enterText(field, '!'); + await tester.pump(); + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await tester.pump(); + expect(find.text('Type a command after !.'), findsOneWidget); + expect(gateway.bodies('chat_shell_run'), isEmpty); + }); + + testWidgets('Run command… in the actions menu runs the typed command', ( + tester, + ) async { + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.tap(find.byKey(segmentedMoreKey).hitTestable().first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Run command…')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('chat-shell-run-field')), + ' ls -la ', + ); + await tester.tap(find.byKey(const Key('chat-shell-run-confirm'))); + // The running card's indicator never settles; let the dialog close. + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(gateway.bodies('chat_shell_run').single['command'], 'ls -la'); + expect(find.text('\$ ls -la'), findsOneWidget); + }); +} diff --git a/app/test/features/chat/shell/chat_shell_fixtures.dart b/app/test/features/chat/shell/chat_shell_fixtures.dart new file mode 100644 index 00000000..5efeb181 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_fixtures.dart @@ -0,0 +1,112 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import '../conversation/chat_thread_fixtures.dart'; + +/// A gateway for one open conversation (session `s`) that answers the shell +/// command requests from recorded state and lets a test push their frames. +class ShellGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + final _frames = StreamController<JsonMap>.broadcast(); + List<JsonMap> runs = const []; + String? refusal; + int _serial = 0; + + @override + Stream<JsonMap> get frames => _frames.stream; + + List<JsonMap> bodies(String type) => [ + for (final call in calls) + if (call.type == type) + (call.fields['chat_shell_run_request'] ?? + call.fields['chat_prompt'] ?? + call.fields['chat_query']) + as JsonMap, + ]; + + @override + Future<JsonMap> call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: fields)); + final body = fields['chat_shell_run_request'] as JsonMap? ?? const {}; + switch (type) { + case 'chat_messages': + return chatPage(const []); + case 'chat_shell_runs': + return {'chat_shell_runs': runs}; + case 'chat_shell_run': + if (refusal != null) throw StateError(refusal!); + return { + 'chat_shell_run': shellRecord( + 'run_${++_serial}', + command: '${body['command']}', + ), + }; + case 'chat_shell_run_output': + return { + 'chat_shell_run': runs.firstWhere((r) => r['id'] == body['run_id']), + }; + } + return <String, dynamic>{}; + } + + void emitRun(JsonMap run) => _frames.add({ + 'type': 'chat_shell_run_event', + 'chat_shell_run_event': { + 'session_id': 's', + 'run_id': run['id'], + 'run': run, + }, + }); + + void emitOutput(String id, String text, int offset) => _frames.add({ + 'type': 'chat_shell_run_event', + 'chat_shell_run_event': { + 'session_id': 's', + 'run_id': id, + 'output': text, + 'offset': offset, + 'end': offset + text.length, + }, + }); + + void close() => _frames.close(); +} + +JsonMap shellRecord( + String id, { + String command = 'make test', + String status = 'running', + int? exitCode, + String output = '', + int durationMs = 0, +}) => { + 'id': id, + 'session_id': 's', + 'command': command, + 'directory': '/home/op/project', + 'status': status, + 'exit_code': ?exitCode, + 'started_at': 1000, + 'ended_at': ?(status == 'running' ? null : 1000 + durationMs), + 'duration_ms': durationMs, + 'output': output, + 'output_bytes': output.length, +}; + +Widget shellThread(ShellGateway gateway, {bool cupertino = false}) { + final thread = ChatThreadView( + gateway: gateway, + sessionId: 's', + syncToken: 0, + onBack: () {}, + drafts: MemoryChatDraftStore(), + ); + return cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: thread)) + : MaterialApp(home: Scaffold(body: thread)); +} diff --git a/app/test/features/chat/shell/chat_shell_run_card_test.dart b/app/test/features/chat/shell/chat_shell_run_card_test.dart new file mode 100644 index 00000000..0fe94039 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_run_card_test.dart @@ -0,0 +1,157 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_shell_fixtures.dart'; + +void main() { + late ShellGateway gateway; + + setUp(() => gateway = ShellGateway()); + tearDown(() => gateway.close()); + + Finder card() => find.bySemanticsIdentifier('chat-shell-run-card'); + + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$host: a running command streams output and stops', ( + tester, + ) async { + gateway.runs = [shellRecord('run_a', output: 'line 1\n')]; + await tester.pumpWidget(shellThread(gateway, cupertino: cupertino)); + await tester.pump(); + + expect(card(), findsOneWidget); + expect(find.text('\$ make test'), findsOneWidget); + expect(find.byKey(const Key('chat-shell-run-running')), findsOneWidget); + gateway.emitOutput('run_a', 'line 2\n', 7); + await tester.pump(); + expect(find.text('line 1\nline 2\n'), findsOneWidget); + expect(find.byKey(const Key('chat-shell-run-share')), findsNothing); + + await tester.tap(find.byKey(const Key('chat-shell-run-stop'))); + await tester.pump(); + expect(gateway.bodies('chat_shell_stop').single['run_id'], 'run_a'); + expect(find.text('Stopping…'), findsOneWidget); + + gateway.emitRun( + shellRecord('run_a', status: 'stopped', durationMs: 2400), + ); + await tester.pump(); + expect(find.byKey(const Key('chat-shell-run-running')), findsNothing); + expect(find.text('Stopped · 2.4 s'), findsOneWidget); + expect(find.byKey(const Key('chat-shell-run-stop')), findsNothing); + // The streamed output stays after the lifecycle frame. + expect(find.text('line 1\nline 2\n'), findsOneWidget); + }); + + testWidgets('$host: finished commands show their exit status', ( + tester, + ) async { + gateway.runs = [ + shellRecord( + 'run_ok', + command: 'true', + status: 'exited', + exitCode: 0, + output: 'fine\n', + durationMs: 120, + ), + shellRecord( + 'run_bad', + command: 'false', + status: 'exited', + exitCode: 1, + output: 'broken\n', + durationMs: 3000, + ), + ]; + await tester.pumpWidget(shellThread(gateway, cupertino: cupertino)); + await tester.pump(); + + expect(card(), findsNWidgets(2)); + expect(find.text('Exit 0 · 120 ms'), findsOneWidget); + expect(find.text('Exit 1 · 3.0 s'), findsOneWidget); + expect(find.byKey(const Key('chat-shell-run-copy')), findsNWidgets(2)); + }); + + testWidgets('$host: Send to agent shares the run once', (tester) async { + gateway.runs = [ + shellRecord('run_a', status: 'exited', exitCode: 0, output: 'ok\n'), + ]; + await tester.pumpWidget(shellThread(gateway, cupertino: cupertino)); + await tester.pump(); + + expect(gateway.calls.where((c) => c.type == 'chat_prompt'), isEmpty); + await tester.tap(find.byKey(const Key('chat-shell-run-share'))); + await tester.pump(); + expect(gateway.bodies('chat_shell_share').single['run_id'], 'run_a'); + expect(find.text('Sent to agent'), findsOneWidget); + await tester.tap(find.byKey(const Key('chat-shell-run-share'))); + await tester.pump(); + expect(gateway.bodies('chat_shell_share'), hasLength(1)); + }); + } + + testWidgets('Copy output copies the retained output', (tester) async { + final copied = <String>[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add('${(call.arguments as Map)['text']}'); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + gateway.runs = [ + shellRecord('run_a', status: 'exited', exitCode: 0, output: 'a\nb\n'), + ]; + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.tap(find.byKey(const Key('chat-shell-run-copy'))); + await tester.pump(); + expect(copied, ['a\nb\n']); + expect(find.text('Copied'), findsOneWidget); + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('a large text scale keeps the card readable', (tester) async { + gateway.runs = [ + shellRecord( + 'run_a', + status: 'exited', + exitCode: 2, + output: List.generate(80, (i) => 'line $i').join('\n'), + ), + ]; + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData( + size: Size(400, 900), + textScaler: TextScaler.linear(2), + ), + child: shellThread(gateway), + ), + ); + await tester.pump(); + expect(tester.takeException(), isNull); + expect(find.textContaining('Exit 2'), findsOneWidget); + final expand = find.byKey(const Key('chat-shell-run-expand')); + await tester.ensureVisible(expand); + await tester.pump(); + await tester.tap(expand); + await tester.pump(); + expect(find.text('Collapse'), findsOneWidget); + }); +}