Show dismissed commands as an answer footer chip; move Copy to the left gutter

Dismissed shell runs leave the transcript and fold into a "N commands"
chip in the footer of the first answer at or after each run (the last
answer for newer runs, or a row of its own without any answer). The chip
opens the turn sheet (wide) or a full-screen page (narrow) listing the
commands; each opens its output read-only with Copy output, Send to agent
and Restore.

On a wide conversation the answer's Copy button moves out of the footer
into a 48 px gutter left of the reading column (chatCopyGutter), shown on
hover or focus on desktops and always on touch; narrow widths keep it in
the footer.
This commit is contained in:
2026-11-09 23:47:14 +00:00
parent f2520a09b8
commit cf9f71f27c
21 changed files with 1534 additions and 77 deletions
@@ -8,3 +8,14 @@ const double kChatReadingWidth = 760;
/// The space on each side of the centred reading column in [width].
double chatReadingInset(double width) =>
math.max(0, (width - kChatReadingWidth) / 2);
/// The strip left of the reading column that holds an answer's Copy button,
/// outside the answer itself.
const double kChatCopyGutterWidth = 48;
/// The copy gutter a transcript [width] wide gives each answer:
/// [kChatCopyGutterWidth] when the margin left of the centred reading column
/// fits it, else 0, and Copy stays in the answer's footer (phones, narrow
/// panes).
double chatCopyGutter(double width) =>
chatReadingInset(width) >= kChatCopyGutterWidth ? kChatCopyGutterWidth : 0;
@@ -59,6 +59,7 @@ import '../../../ui/adaptive/segmented_bar_overlay.dart';
import '../../../ui/layout/app_sheet_header.dart';
import '../../../ui/layout/wheel_scroll_forwarding.dart';
import 'chat_reading_width.dart';
import '../ui/transcript/chat_copy_gutter.dart';
import 'chat_pane_presentation.dart';
import 'chat_thread_header.dart';
import 'chat_transcript_anchor.dart';
@@ -67,6 +68,8 @@ 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_history.dart';
import '../shell/chat_shell_history_chip.dart';
import '../shell/chat_shell_dismiss.dart';
import '../shell/chat_shell_run.dart';
import '../shell/chat_shell_run_card.dart';
@@ -1053,11 +1056,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
);
final notices = _dismissals.visible(allNotices);
final compactionNotice = _noticeOf(notices, ChatNoticeKind.compaction);
// 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);
// The operator's own shell commands sit among the turns by start time;
// dismissed ones fold into a chip under the answer that followed them.
final rows = attachChatShellHistory(
withChatShellRunRows([
for (final row in allRows)
if (!_hiddenRunningCompaction(row)) row,
], _shellRuns.runs),
_shellRuns.dismissedRuns,
);
// 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
@@ -1129,29 +1136,42 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// Rows keep to the centred reading column on a wide
// window; the margins beside it still scroll the list.
final side = chatReadingInset(constraints.maxWidth);
// Answers draw Copy in a strip left of the column; every
// other row keeps to the column by insetting past it.
final gutter = chatCopyGutter(constraints.maxWidth);
final media = MediaQuery.paddingOf(context);
final transcript = [
for (var index = 0; index < rows.length; index++)
Padding(
key: ValueKey<String>(keys[index]),
padding: const EdgeInsets.symmetric(horizontal: 16),
padding: EdgeInsets.only(
left:
16 +
(rows[index]['kind'] == 'assistant' ? 0 : gutter),
right: 16,
),
// Slivers mount only visible rows. Defer constructing
// their chips and checking cached widgets until then,
// rather than visiting the entire history per delta.
child: Builder(
builder: (_) => _entering(
rows[index],
_transcriptRow(
child: ChatCopyGutter(
width: rows[index]['kind'] == 'assistant'
? gutter
: 0,
child: Builder(
builder: (_) => _entering(
rows[index],
keys[index],
onDismissCompaction:
compactionNotice != null &&
chatNoticeActivityCondition(
rows[index],
) ==
compactionNotice.condition
? () => _dismiss(compactionNotice)
: null,
_transcriptRow(
rows[index],
keys[index],
onDismissCompaction:
compactionNotice != null &&
chatNoticeActivityCondition(
rows[index],
) ==
compactionNotice.condition
? () => _dismiss(compactionNotice)
: null,
),
),
),
),
@@ -1177,12 +1197,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
? null
: ValueKey<String>(keys[split]),
padding: EdgeInsets.fromLTRB(
side,
side - gutter,
media.top + 8,
side,
8,
),
children: [
children: chatCopyGutterInset(gutter, transcript, [
if (initialLoad)
Padding(
key: const Key('chat-thread-loading'),
@@ -1278,7 +1298,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
notice: notice,
onDismiss: _dismiss,
),
],
]),
),
),
if (showJump)
@@ -1538,6 +1558,16 @@ class _ChatThreadViewState extends State<ChatThreadView> {
runId: '${row['run_id']}',
);
}
if (kind == chatShellHistoryRowKind) {
// A chat with no answer yet keeps its dismissed commands on their own.
return Align(
alignment: AlignmentDirectional.centerStart,
child: ChatShellHistoryChip(
controller: _shellRuns,
runIds: chatShellHistoryIds(row),
),
);
}
if (kind == chatShownRowKind) {
return ChatShownCard(
row: row,
@@ -1563,6 +1593,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
summary: Map<String, dynamic>.from(diff),
load: () => _controller.turnDiff('${diff['turn_id']}'),
),
if (chatShellHistoryIds(row) case final ids when ids.isNotEmpty)
ChatShellHistoryChip(controller: _shellRuns, runIds: ids),
];
if (kind == 'permissions') {
return Align(
@@ -1587,7 +1619,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
return _rowWidgets.widgetFor(
key,
row,
[delivery, cupertino, onRemove != null, _images, _controller, _composer],
[
delivery,
cupertino,
onRemove != null,
_images,
_controller,
_composer,
_shellRuns,
],
() => ChatMessageView(
row: row,
textBuilder: chatMarkdownText,
@@ -9,7 +9,6 @@ import 'chat_shell_runs_controller.dart';
const String chatShellDismissLabel = 'Dismiss';
const String chatShellDismissAllLabel = 'Dismiss all finished commands';
/// The card's Dismiss button, offered once the command has finished.
class ChatShellDismissButton extends StatelessWidget {
const ChatShellDismissButton({
@@ -0,0 +1,65 @@
import '../../../core/api_gateway.dart';
import 'chat_shell_run.dart';
/// The row field that carries an answer's dismissed command ids, oldest
/// first: what its footer's "N commands" chip lists.
const String chatShellHistoryField = 'shellHistory';
/// The transcript row kind of the history chip a chat with no answer shows.
const String chatShellHistoryRowKind = 'shell_history';
/// Attaches each dismissed run to an answer's footer as [chatShellHistoryField]:
/// the first assistant reply created at or after the run started, or the last
/// reply for a run newer than every reply. A reply without a recorded time is
/// only chosen as that last reply. With no assistant reply at all, one
/// [chatShellHistoryRowKind] row at the end holds every run.
List<JsonMap> attachChatShellHistory(
List<JsonMap> rows,
List<ChatShellRun> dismissed,
) {
if (dismissed.isEmpty) return rows;
final replies = [
for (var i = 0; i < rows.length; i++)
if (rows[i]['kind'] == 'assistant') i,
];
final ordered = [...dismissed]
..sort((a, b) => a.startedAt.compareTo(b.startedAt));
if (replies.isEmpty) {
return [
...rows,
{
'kind': chatShellHistoryRowKind,
'key': 'chat-shell-history',
chatShellHistoryField: [for (final run in ordered) run.id],
},
];
}
final assigned = <int, List<String>>{};
for (final run in ordered) {
final index = replies.firstWhere((i) {
final created = rows[i]['created_at'];
return created is num && created >= run.startedAt;
}, orElse: () => replies.last);
(assigned[index] ??= []).add(run.id);
}
return [
for (var i = 0; i < rows.length; i++)
if (assigned[i] case final ids?)
{...rows[i], chatShellHistoryField: ids}
else
rows[i],
];
}
/// The dismissed command ids [row] carries, oldest first.
List<String> chatShellHistoryIds(JsonMap row) => [
for (final id in row[chatShellHistoryField] as List? ?? const []) '$id',
];
/// The chip's label, e.g. `2 commands`.
String chatShellHistoryLabel(int count) =>
count == 1 ? '1 command' : '$count commands';
/// The chip's accessible name.
String chatShellHistorySemantics(int count) =>
'${chatShellHistoryLabel(count)} dismissed, open command history';
@@ -0,0 +1,82 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../shell/list_detail_policy.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_turn_chip.dart';
import 'chat_shell_history.dart';
import 'chat_shell_history_view.dart';
import 'chat_shell_runs_controller.dart';
/// The dismissed commands attached to an answer, as a chip in its footer
/// beside the change and tool chips: `2 commands`. A wide window opens the
/// list in the turn sheet; a narrow one opens it as a full-screen page.
class ChatShellHistoryChip extends StatelessWidget {
const ChatShellHistoryChip({
super.key,
required this.controller,
required this.runIds,
});
final ChatShellRunsController controller;
/// The dismissed runs this chip lists, oldest first.
final List<String> runIds;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
return ChatTurnChip(
chipKey: const Key('chat-shell-history-chip'),
leading: Icon(
cupertino
? CupertinoIcons.chevron_left_slash_chevron_right
: Icons.terminal,
size: 14,
color: color,
),
label: chatShellHistoryLabel(runIds.length),
color: color,
semanticsLabel: chatShellHistorySemantics(runIds.length),
ellipsizeLabel: true,
open: _open,
);
}
Future<void> _open(BuildContext context, bool cupertino) {
if (MediaQuery.sizeOf(context).width >= kListDetailMinWidth) {
return showChatTurnSheet(
context,
cupertino,
ChatShellHistoryView(controller: controller, runIds: runIds),
);
}
final view = ChatShellHistoryView(
controller: controller,
runIds: runIds,
inSheet: false,
);
const title = Text(chatShellHistoryTitle);
return Navigator.of(context).push<void>(
cupertino
? CupertinoPageRoute<void>(
fullscreenDialog: true,
builder: (_) => CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: title),
child: SafeArea(child: view),
),
)
: MaterialPageRoute<void>(
fullscreenDialog: true,
builder: (_) => Scaffold(
appBar: AppBar(title: title),
body: SafeArea(child: view),
),
),
);
}
}
@@ -0,0 +1,277 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/text/monospace.dart';
import '../conversation/chat_card_styles.dart';
import 'chat_shell_card_actions.dart';
import 'chat_shell_run.dart';
import 'chat_shell_runs_controller.dart';
import 'chat_shell_status.dart';
import 'chat_shell_terminal_session.dart';
import 'chat_shell_terminal_view.dart';
/// Opens a dismissed command's output read-only, full screen.
Future<void> openChatShellHistoryOutput(
BuildContext context, {
required ChatShellRunsController controller,
required String runId,
required bool cupertino,
}) {
Widget page(BuildContext _) => ChatShellHistoryOutputPage(
controller: controller,
runId: runId,
cupertino: cupertino,
);
return Navigator.of(context).push<void>(
cupertino
? CupertinoPageRoute<void>(builder: page)
: MaterialPageRoute<void>(builder: page),
);
}
/// One dismissed command: everything the server kept of its output in the
/// card's terminal view (read-only), with Copy output, Send to agent and
/// Restore, which puts its card back in the transcript and closes the page.
class ChatShellHistoryOutputPage extends StatefulWidget {
const ChatShellHistoryOutputPage({
super.key,
required this.controller,
required this.runId,
required this.cupertino,
});
final ChatShellRunsController controller;
final String runId;
final bool cupertino;
@override
State<ChatShellHistoryOutputPage> createState() =>
_ChatShellHistoryOutputPageState();
}
class _ChatShellHistoryOutputPageState
extends State<ChatShellHistoryOutputPage> {
late final Future<ChatShellRun> _full = widget.controller.fullOutput(
widget.runId,
);
ChatShellTerminalSession? _session;
bool _copied = false;
String? _refusal;
Timer? _reset;
@override
void dispose() {
_reset?.cancel();
super.dispose();
}
Future<void> _copy(ChatShellRun full) async {
final text = full.terminal || full.text.isNotEmpty
? full.text
: full.output;
await Clipboard.setData(ClipboardData(text: text));
if (!mounted) return;
setState(() => _copied = true);
_reset?.cancel();
_reset = Timer(const Duration(seconds: 2), () {
if (mounted) setState(() => _copied = false);
});
}
Future<void> _restore() async {
final refusal = await widget.controller.restore([widget.runId]);
if (!mounted) return;
if (refusal == null) {
Navigator.of(context).maybePop();
} else {
setState(() => _refusal = refusal);
}
}
@override
Widget build(BuildContext context) {
final cupertino = widget.cupertino;
final held = widget.controller.dismissedRun(widget.runId);
final title = Text(
held == null ? 'Command' : '\$ ${held.command}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontFamily: appMonospaceFamily),
);
final body = SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: FutureBuilder<ChatShellRun>(
future: _full,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(
"Couldn't read the output: ${snapshot.error}",
style: chatCardSecondaryStyle(context, cupertino),
);
}
final full = snapshot.data;
if (full == null) {
return Center(
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
);
}
return _content(context, full);
},
),
),
);
if (cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: title),
child: body,
);
}
return Scaffold(
appBar: AppBar(title: title),
body: body,
);
}
Widget _content(BuildContext context, ChatShellRun full) {
final cupertino = widget.cupertino;
final session = _session ??= ChatShellTerminalSession(
full,
onInput: (_) {},
onResize: (_, _) {},
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
ChatShellStatus(run: full, cupertino: cupertino),
if (full.directory.isNotEmpty)
Text(
full.directory,
style: chatCardSecondaryStyle(context, cupertino),
),
],
),
),
Expanded(
child: full.output.isEmpty
? Text(
'No output.',
key: const Key('chat-shell-output-empty'),
style: chatCardSecondaryStyle(context, cupertino),
)
: ChatShellTerminalView(
session: session,
cupertino: cupertino,
fill: true,
),
),
const SizedBox(height: 8),
ListenableBuilder(
listenable: widget.controller,
builder: (context, _) => _actions(context, full),
),
],
);
}
Widget _actions(BuildContext context, ChatShellRun full) {
final controller = widget.controller;
final share = controller.shareState(widget.runId);
final error = _refusal ?? controller.errorFor(widget.runId);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Wrap(
spacing: 8,
runSpacing: 4,
children: [
if (full.outputBytes > 0)
_button(
key: const Key('chat-shell-history-copy'),
label: _copied ? chatShellCopiedLabel : chatShellCopyLabel,
material: _copied ? Icons.check : Icons.copy_outlined,
cupertino: _copied
? CupertinoIcons.checkmark
: CupertinoIcons.doc_on_doc,
onPressed: () => unawaited(_copy(full)),
),
_button(
key: const Key('chat-shell-history-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(widget.runId))
: null,
),
_button(
key: const Key('chat-shell-history-page-restore'),
label: 'Restore',
material: Icons.restore,
cupertino: CupertinoIcons.arrow_counterclockwise,
onPressed: () => unawaited(_restore()),
),
],
),
if (error != null)
Semantics(
liveRegion: true,
child: Text(
error,
style: chatCardSecondaryStyle(
context,
widget.cupertino,
)?.copyWith(color: chatCardErrorColor(context, widget.cupertino)),
),
),
],
);
}
Widget _button({
required Key key,
required String label,
required IconData material,
required IconData cupertino,
required VoidCallback? onPressed,
}) {
if (widget.cupertino) {
return CupertinoButton(
key: key,
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: onPressed,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [Icon(cupertino), const SizedBox(width: 6), Text(label)],
),
);
}
return TextButton.icon(
key: key,
onPressed: onPressed,
icon: Icon(material),
label: Text(label),
);
}
}
@@ -0,0 +1,186 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/text/monospace.dart';
import '../conversation/chat_card_styles.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_shell_history_output_page.dart';
import 'chat_shell_run.dart';
import 'chat_shell_runs_controller.dart';
import 'chat_shell_status.dart';
const String chatShellHistoryTitle = 'Dismissed commands';
const String chatShellRestoreLabel = 'Restore';
const String chatShellCommandNotKept = 'Command not kept';
const String chatShellOutputNotKept = 'Output not kept';
/// The dismissed commands of one answer: each command with its exit status,
/// how long it ran and when. Tapping one opens its output read-only; Restore
/// puts its card back in the transcript.
class ChatShellHistoryView extends StatefulWidget {
const ChatShellHistoryView({
super.key,
required this.controller,
required this.runIds,
this.inSheet = true,
});
final ChatShellRunsController controller;
final List<String> runIds;
/// In the turn sheet (shrinks to its content) rather than a page.
final bool inSheet;
@override
State<ChatShellHistoryView> createState() => _ChatShellHistoryViewState();
}
class _ChatShellHistoryViewState extends State<ChatShellHistoryView> {
final Map<String, String> _refusals = {};
Future<void> _restore(String id) async {
final refusal = await widget.controller.restore([id]);
if (!mounted) return;
setState(() {
if (refusal == null) {
_refusals.remove(id);
} else {
_refusals[id] = refusal;
}
});
}
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final list = ListenableBuilder(
listenable: widget.controller.membership,
builder: (context, _) {
final runs = [
for (final id in widget.runIds) ?widget.controller.dismissedRun(id),
];
return ListView(
key: const Key('chat-shell-history-list'),
shrinkWrap: widget.inSheet,
padding: const EdgeInsets.symmetric(vertical: 8),
children: [
if (widget.inSheet)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
child: Text(
chatShellHistoryTitle,
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
if (runs.isEmpty)
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Every command here was restored to the transcript.',
style: chatCardSecondaryStyle(context, cupertino),
),
),
for (final run in runs) _entry(context, run, cupertino),
],
);
},
);
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
// Entries are Material list tiles inside a Cupertino surface too.
final content = Material(
type: MaterialType.transparency,
child: DefaultTextStyle.merge(style: style, child: list),
);
if (!widget.inSheet) return content;
return ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: content,
);
}
Widget _entry(BuildContext context, ChatShellRun run, bool cupertino) {
final secondary = chatCardSecondaryStyle(context, cupertino);
final refusal = _refusals[run.id];
final command = run.purged || run.command.isEmpty
? Text(chatShellCommandNotKept, style: secondary)
: Text(
'\$ ${run.command}',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: appMonospaceFamily,
fontWeight: FontWeight.w600,
),
);
final details = Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
ChatShellStatus(run: run, cupertino: cupertino),
Text(chatShellRunTime(context, run.startedAt), style: secondary),
if (run.purged) Text(chatShellOutputNotKept, style: secondary),
if (refusal != null)
Text(
refusal,
key: const Key('chat-shell-history-refusal'),
style: secondary?.copyWith(
color: chatCardErrorColor(context, cupertino),
),
),
],
);
final restore = run.purged
? null
: cupertino
? CupertinoButton(
key: ValueKey<String>('chat-shell-history-restore-${run.id}'),
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: () => unawaited(_restore(run.id)),
child: const Text(chatShellRestoreLabel),
)
: TextButton(
key: ValueKey<String>('chat-shell-history-restore-${run.id}'),
onPressed: () => unawaited(_restore(run.id)),
child: const Text(chatShellRestoreLabel),
);
return ListTile(
key: ValueKey<String>('chat-shell-history-${run.id}'),
title: command,
subtitle: Padding(padding: const EdgeInsets.only(top: 4), child: details),
trailing: restore,
enabled: !run.purged,
onTap: run.purged
? null
: () => unawaited(
openChatShellHistoryOutput(
context,
controller: widget.controller,
runId: run.id,
cupertino: cupertino,
),
),
);
}
}
/// When a command started, as the operator's local date and time.
String chatShellRunTime(BuildContext context, int startedAt) {
if (startedAt <= 0) return '';
final instant = DateTime.fromMillisecondsSinceEpoch(startedAt).toLocal();
final material = Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
);
final hour = instant.hour.toString().padLeft(2, '0');
final minute = instant.minute.toString().padLeft(2, '0');
if (material == null) return '${instant.day}/${instant.month} $hour:$minute';
return '${material.formatShortMonthDay(instant)} · $hour:$minute';
}
@@ -31,6 +31,8 @@ class ChatShellRun {
this.cols = 0,
this.rows = 0,
this.text = '',
this.dismissedAt = 0,
this.purged = false,
});
final String id;
@@ -68,6 +70,13 @@ class ChatShellRun {
/// removed); only a whole-output readback carries it.
final String text;
/// When the operator dismissed the run (epoch ms; 0 when not dismissed).
final int dismissedAt;
/// True when an older server deleted the dismissed run's command and
/// output: only its status and times are left, and it cannot be restored.
final bool purged;
/// Whether earlier output is not shown here.
bool get truncated => outputStart > 0 || gap;
@@ -111,6 +120,8 @@ class ChatShellRun {
cols: _int(value['cols']),
rows: _int(value['rows']),
text: '${value['text'] ?? ''}',
dismissedAt: _int(value['dismissed_at']),
purged: value['purged'] == true,
);
}
@@ -137,6 +148,8 @@ class ChatShellRun {
cols: next.cols == 0 ? cols : next.cols,
rows: next.rows == 0 ? rows : next.rows,
text: text,
dismissedAt: next.dismissedAt,
purged: next.purged,
);
/// This run with one live output chunk covering bytes [offset, end). A
@@ -18,7 +18,8 @@ import 'chat_shell_terminal_page.dart';
/// One operator command in the transcript, as a terminal card in the reading
/// column: the command and folder, its terminal (typed into while it runs),
/// a spinner and Stop while it runs, then its exit status, Copy output and
/// Send to agent, and Dismiss (for every client of the chat, with Undo). A
/// Send to agent, and Dismiss (for every client of the chat; the run moves
/// into the answer's command history chip, which can restore it). A
/// running command has no Dismiss: Stop it first. Full screen opens the same
/// terminal over the whole window.
///
@@ -51,6 +51,10 @@ class ChatShellRunsController extends ChangeNotifier {
/// Runs dismissed here or by another client: a readback racing the
/// dismissal does not bring their cards back.
final Set<String> _gone = {};
/// The dismissed runs this copy holds, shown collapsed in the transcript's
/// command history rather than as cards.
final Map<String, ChatShellRun> _dismissed = {};
bool _disposed = false;
int _generation = 0;
@@ -75,11 +79,16 @@ class ChatShellRunsController extends ChangeNotifier {
Future<void> refresh() async {
final token = ++_generation;
try {
final (:runs, :dismissed) = await _repository.runs(sessionId);
final (:runs, :dismissed, :dismissedRuns) = await _repository.runs(
sessionId,
);
if (_disposed || token != _generation) return;
dismissed.forEach(_remove);
_holdDismissed(dismissedRuns);
for (final run in runs) {
if (_gone.contains(run.id)) continue;
// Restored by another client while this copy missed the frame.
_dismissed.remove(run.id);
final held = _runs[run.id];
if (held != null &&
held.running &&
@@ -204,7 +213,10 @@ class ChatShellRunsController extends ChangeNotifier {
if (frame is! Map || frame['session_id'] != sessionId) return;
final id = '${frame['run_id'] ?? ''}';
if (frame['dismissed'] == true) {
final known = _runs.containsKey(id) || _dismissed.containsKey(id);
_remove(id);
// Another client dismissed a run this copy never held: read it.
if (!known) unawaited(refresh());
_changed(membership: true);
return;
}
@@ -212,6 +224,7 @@ class ChatShellRunsController extends ChangeNotifier {
if (record != null) {
// A restored run (another client's Undo) comes back without output.
if (_gone.remove(record.id) && !record.running) unawaited(refresh());
_dismissed.remove(record.id);
final held = _runs[record.id];
final next = held == null ? record : held.withLifecycle(record);
_runs[record.id] = next;
@@ -1,11 +1,21 @@
part of 'chat_shell_runs_controller.dart';
/// Dismissing finished command cards for every client of the chat, and the
/// Undo that restores them while the server still keeps them.
/// Dismissing finished command cards for every client of the chat, the
/// dismissed runs the server keeps (the transcript's command history), and
/// Restore, which puts a card back.
extension ChatShellRunsDismissal on ChatShellRunsController {
/// The dismissed runs this copy holds, oldest first.
List<ChatShellRun> get dismissedRuns =>
[..._dismissed.values]
..sort((a, b) => a.startedAt.compareTo(b.startedAt));
/// One dismissed run, or null once it was restored (or aged out).
ChatShellRun? dismissedRun(String id) => _dismissed[id];
/// Dismisses finished runs [ids] for every client of the chat: their cards
/// go at once and come back (with the refusal) if the server refuses.
/// Returns the refusal, or null. A running command is never dismissed.
/// go at once into the command history and come back (with the refusal) if
/// the server refuses. Returns the refusal, or null. A running command is
/// never dismissed.
Future<String?> dismiss(List<String> ids) async {
final removed = [
for (final id in ids)
@@ -24,6 +34,7 @@ extension ChatShellRunsDismissal on ChatShellRunsController {
final reason = _reason(error);
for (final run in removed) {
_gone.remove(run.id);
_dismissed.remove(run.id);
_runs[run.id] = run;
_errors[run.id] = reason;
}
@@ -32,14 +43,15 @@ extension ChatShellRunsDismissal on ChatShellRunsController {
}
}
/// Undoes the dismissal of [ids] while the server still keeps them.
/// Returns the refusal, or null.
/// Puts dismissed runs [ids] back in the transcript as cards, for every
/// client. Returns the refusal, or null.
Future<String?> restore(List<String> ids) async {
try {
final restored = await _repository.restore(sessionId, ids);
if (_disposed) return null;
for (final run in restored) {
_gone.remove(run.id);
_dismissed.remove(run.id);
final held = _runs[run.id];
final keep = held != null && held.outputEnd >= run.outputEnd;
_runs[run.id] = keep ? held.withLifecycle(run) : run;
@@ -52,7 +64,24 @@ extension ChatShellRunsDismissal on ChatShellRunsController {
}
}
/// The dismissed run [id] with everything the server kept of its output
/// and its plain-text rendering, for the history's read-only output view.
Future<ChatShellRun> fullOutput(String id) =>
_repository.output(sessionId, id);
/// Folds a readback's dismissed runs into the history. Runs this copy
/// dismissed but the readback does not list yet stay held.
void _holdDismissed(List<ChatShellRun> runs) {
for (final run in runs) {
_gone.add(run.id);
_dismissed[run.id] = run;
}
}
/// Takes [id]'s card out of the transcript; a held copy moves into the
/// command history.
void _remove(String id) {
if (_runs[id] case final run?) _dismissed[id] = run;
_gone.add(id);
_runs.remove(id);
_errors.remove(id);
@@ -57,15 +57,25 @@ class ChatShellRunsRepository {
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,
/// and the ids of its dismissed runs (whose cards go away).
Future<({List<ChatShellRun> runs, Set<String> dismissed})> runs(
String sessionId,
) async {
/// The session's recorded runs, oldest first, each with its output tail;
/// the ids of its dismissed runs (whose cards go away); and the dismissed
/// runs themselves, which a server that keeps them also sends.
Future<
({
List<ChatShellRun> runs,
Set<String> dismissed,
List<ChatShellRun> dismissedRuns,
})
>
runs(String sessionId) async {
final reply = await gateway.call('chat_shell_runs', {
'chat_query': {'session_id': sessionId},
});
return (runs: _records(reply), dismissed: _ids(reply));
return (
runs: _records(reply),
dismissed: _ids(reply),
dismissedRuns: _records(reply, 'chat_shell_dismissed_runs'),
);
}
/// Dismisses finished runs for every client of the chat; the reply names
@@ -78,8 +88,8 @@ class ChatShellRunsRepository {
),
);
/// Undoes a dismissal still inside the server's undo window; the reply is
/// the restored runs with their output tail.
/// Undoes a dismissal (at any time; an older server only within its undo
/// window); the reply is the restored runs with their output tail.
Future<List<ChatShellRun>> restore(
String sessionId,
List<String> runIds,
@@ -87,8 +97,11 @@ class ChatShellRunsRepository {
await gateway.call('chat_shell_restore', _body(sessionId, runIds: runIds)),
);
List<ChatShellRun> _records(JsonMap reply) {
final value = reply['chat_shell_runs'];
List<ChatShellRun> _records(
JsonMap reply, [
String field = 'chat_shell_runs',
]) {
final value = reply[field];
return [
if (value is List)
for (final item in value) ?ChatShellRun.fromJson(item),
@@ -0,0 +1,110 @@
import 'package:flutter/material.dart';
import '../../../../ui/adaptive/platform.dart';
/// The width of the strip left of the reading column that an answer row
/// draws its Copy button in (`chatCopyGutter`); 0 when there is no room, and
/// Copy stays in the answer's footer.
class ChatCopyGutter extends InheritedWidget {
const ChatCopyGutter({super.key, required this.width, required super.child});
final double width;
static double of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ChatCopyGutter>()?.width ?? 0;
@override
bool updateShouldNotify(ChatCopyGutter oldWidget) => width != oldWidget.width;
}
/// The transcript's [children] when the list starts [gutter] left of the
/// reading column: every child except the transcript [rows] (which inset
/// themselves) is inset past the gutter, so it keeps to the column.
List<Widget> chatCopyGutterInset(
double gutter,
List<Widget> rows,
List<Widget> children,
) {
if (gutter <= 0) return children;
final own = Set<Widget>.identity()..addAll(rows);
return [
for (final child in children)
if (own.contains(child))
child
else
Padding(
key: child.key,
padding: EdgeInsets.only(left: gutter),
child: child,
),
];
}
/// An answer with its Copy button in the gutter to its left, bottom-aligned
/// with the answer's footer row. On a desktop the button shows while the
/// pointer is over the answer or the button has focus; it stays in the
/// focus order and the semantics tree when hidden. Touch platforms always
/// show it.
class ChatCopyGutterRow extends StatefulWidget {
const ChatCopyGutterRow({
super.key,
required this.width,
required this.copy,
required this.child,
});
final double width;
/// The Copy button, or null when the answer has nothing to copy yet.
final Widget? copy;
final Widget child;
@override
State<ChatCopyGutterRow> createState() => _ChatCopyGutterRowState();
}
class _ChatCopyGutterRowState extends State<ChatCopyGutterRow> {
bool _hovered = false;
bool _focused = false;
@override
Widget build(BuildContext context) {
final hover = prefersCompactHitTargets(context);
final copy = widget.copy;
final row = Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
SizedBox(
key: const Key('chat-copy-gutter'),
width: widget.width,
child: copy == null
? null
: Align(
alignment: Alignment.bottomRight,
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onFocusChange: (focused) =>
setState(() => _focused = focused),
child: AnimatedOpacity(
key: const Key('chat-copy-gutter-visibility'),
opacity: !hover || _hovered || _focused ? 1 : 0,
duration: const Duration(milliseconds: 120),
alwaysIncludeSemantics: true,
child: copy,
),
),
),
),
Flexible(child: widget.child),
],
);
if (!hover || copy == null) return row;
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: row,
);
}
}
@@ -10,6 +10,7 @@ import 'chat_attachment_gallery.dart';
import '../../domain/chat_tool_calls.dart';
import '../../domain/chat_transcript.dart';
import 'chat_copy_button.dart';
import 'chat_copy_gutter.dart';
import 'chat_link_text.dart';
import 'chat_message_bubble.dart';
import 'chat_turn_activity_view.dart';
@@ -49,6 +50,9 @@ class ChatMessageView extends StatelessWidget {
final role = user ? 'User' : 'Assistant';
final cupertino = _isCupertino(context);
final content = user ? _userParts(context) : _agentParts(context);
// A wide window draws an answer's Copy in the gutter left of the reading
// column; without room it stays at the start of the answer's footer.
final gutter = user ? 0.0 : ChatCopyGutter.of(context);
// No visible role label: side and surface say who spoke and the row's
// semantics label names the role. The operator's turn is a neutral bubble
// that shrinks to its content; the agent's answer sits on the page with no
@@ -79,14 +83,15 @@ class ChatMessageView extends StatelessWidget {
constraints: BoxConstraints(
maxWidth: user
? (constraints.maxWidth * 0.85).clamp(0, 560).toDouble()
: 720,
: 720 + gutter,
),
child: user
? _userTurn(cupertino, content, body)
: _agentTurn(
: _agentRow(
context,
content,
ChatAgentSurface(cupertino: cupertino, child: body),
gutter,
),
),
),
@@ -174,9 +179,34 @@ class ChatMessageView extends StatelessWidget {
return widgets;
}
/// The answer, with its Copy button in the [gutter] to its left when there
/// is one, or else first in its footer.
Widget _agentRow(
BuildContext context,
List<Widget> content,
Widget answer,
double gutter,
) {
final copyText = row['streaming'] == true ? '' : _answerText(_partsOf(row));
final copy = copyText.isEmpty
? null
: ChatCopyButton(text: copyText, cupertino: _isCupertino(context));
if (gutter <= 0) return _agentTurn(context, content, answer, copy);
return ChatCopyGutterRow(
width: gutter,
copy: copy,
child: _agentTurn(context, content, answer, null),
);
}
/// Stable activity precedes the answer; permission summaries and recorded
/// model remain beneath it. Pending interaction cards are rendered separately.
Widget _agentTurn(BuildContext context, List<Widget> content, Widget answer) {
Widget _agentTurn(
BuildContext context,
List<Widget> content,
Widget answer,
Widget? copy,
) {
final parts = _partsOf(row);
final reasoning = [
for (final part in parts)
@@ -189,10 +219,8 @@ class ChatMessageView extends StatelessWidget {
if (isChatToolPart(part)) part,
];
final model = '${row['model'] ?? ''}'.trim();
final copyText = row['streaming'] == true ? '' : _answerText(parts);
final footer = <Widget>[
if (copyText.isNotEmpty)
ChatCopyButton(text: copyText, cupertino: _isCupertino(context)),
?copy,
...this.footer,
if (model.isNotEmpty)
Text(