Run shell commands from the chat composer and show them as cards

A draft starting with ! shows a Shell mode indicator and runs through
chat_shell_run instead of being sent to the agent; the chat's actions menu
gains Run command. Each run is a terminal-style card among the turns with
live output, Stop, its exit status, Copy output and Send to agent.
This commit is contained in:
2026-11-09 16:08:39 +00:00
parent e6bc57c901
commit a6f0f0a1cb
20 changed files with 1812 additions and 10 deletions
@@ -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<ChatShellCardActions> createState() => _ChatShellCardActionsState();
}
class _ChatShellCardActionsState extends State<ChatShellCardActions> {
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<void> _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),
);
}
}
@@ -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 =
'!<command> — 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<JsonMap> withChatShellRunRows(
List<JsonMap> rows,
List<ChatShellRun> runs,
) {
if (runs.isEmpty) return rows;
final ordered = [...runs]..sort((a, b) => a.startedAt.compareTo(b.startedAt));
final merged = <JsonMap>[];
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<String, dynamic>.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';
}
@@ -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;
}
@@ -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),
),
],
),
),
),
);
}
}
@@ -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<ChatShellOutputView> createState() => _ChatShellOutputViewState();
}
class _ChatShellOutputViewState extends State<ChatShellOutputView> {
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);
}
}
@@ -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;
@@ -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<ChatShellRunCard> createState() => _ChatShellRunCardState();
}
class _ChatShellRunCardState extends State<ChatShellRunCard> {
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<String>('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)),
),
),
],
);
}
}
@@ -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<String?> showChatShellRunDialog(
BuildContext context, {
required bool cupertino,
}) => cupertino
? showCupertinoDialog<String>(
context: context,
barrierDismissible: true,
builder: (_) => const ChatShellRunDialog(cupertino: true),
)
: showDialog<String>(
context: context,
builder: (_) => const ChatShellRunDialog(cupertino: false),
);
class ChatShellRunDialog extends StatefulWidget {
const ChatShellRunDialog({super.key, required this.cupertino});
final bool cupertino;
@override
State<ChatShellRunDialog> createState() => _ChatShellRunDialogState();
}
class _ChatShellRunDialogState extends State<ChatShellRunDialog> {
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),
),
],
);
}
}
@@ -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<JsonMap>? _frames;
final Map<String, ChatShellRun> _runs = {};
final ValueNotifier<int> _membership = ValueNotifier<int>(0);
final Set<String> _stopping = {};
final Map<String, ChatShellShareState> _shares = {};
final Map<String, String> _errors = {};
bool _disposed = false;
int _generation = 0;
Listenable get membership => _membership;
List<ChatShellRun> 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<void> 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<String?> 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<void> 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<void> 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<ChatShellRun?> 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();
}
}
@@ -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<ChatShellRun> run(String sessionId, String command) async => _record(
await gateway.call('chat_shell_run', _body(sessionId, command: command)),
);
Future<void> 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<List<ChatShellRun>> 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<ChatShellRun> 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<void> 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;
}
}
@@ -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,
);
}
}
@@ -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<String>('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<void> 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);
}
}