diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index d24ff72f..349d5b6e 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -66,6 +66,7 @@ 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_dismiss.dart'; import '../shell/chat_shell_run.dart'; import '../shell/chat_shell_run_card.dart'; import '../shell/chat_shell_runs_controller.dart'; @@ -1344,6 +1345,8 @@ class _ChatThreadViewState extends State { canGoBack, // The thinking control says when a turn is running. _controller.running, + // The More menu offers Dismiss all finished commands only with one. + _shellRuns.finishedIds.isNotEmpty, ], () => _buildHeader(session, inShellBar, canGoBack, answeredBy)); } @@ -1407,6 +1410,8 @@ class _ChatThreadViewState extends State { ?widget.sidebarControl, ...widget.paneControls, chatShellRunMenuAction(onPressed: _runShellFromMenu), + if (_shellRuns.finishedIds.isNotEmpty) + chatShellDismissAllMenuAction(onPressed: _dismissFinishedShellRuns), ], controls: [ if (hasModel) @@ -1453,6 +1458,19 @@ class _ChatThreadViewState extends State { ), ); + void _dismissFinishedShellRuns() => unawaited( + dismissChatShellRuns( + context, + _shellRuns, + _shellRuns.finishedIds, + cupertino: chatControlsStyleOf(context) == ChatControlsStyle.cupertino, + onRefused: (refusal) => _showCommandNotice( + "Couldn't dismiss the commands: $refusal", + failed: true, + ), + ), + ); + ChatNotice? _noticeOf(List notices, ChatNoticeKind kind) { for (final notice in notices) { if (notice.kind == kind) return notice; diff --git a/app/lib/features/chat/shell/chat_shell_dismiss.dart b/app/lib/features/chat/shell/chat_shell_dismiss.dart new file mode 100644 index 00000000..22006dc2 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_dismiss.dart @@ -0,0 +1,166 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/segmented_bar_overflow.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'chat_shell_runs_controller.dart'; + +const String chatShellDismissLabel = 'Dismiss'; +const String chatShellDismissAllLabel = 'Dismiss all finished commands'; +const String chatShellUndoLabel = 'Undo'; + +/// How long the Undo notice stays. The server keeps a dismissed run +/// restorable for longer (protocol ChatShellRunUndoWindow, 30 s). +const Duration chatShellUndoDuration = Duration(seconds: 5); + +/// The card's Dismiss button, offered once the command has finished. +class ChatShellDismissButton extends StatelessWidget { + const ChatShellDismissButton({ + super.key, + required this.cupertino, + required this.onPressed, + }); + + final bool cupertino; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + if (!cupertino) { + return IconButton( + key: const Key('chat-shell-run-dismiss'), + tooltip: chatShellDismissLabel, + icon: const Icon(Icons.close), + onPressed: onPressed, + ); + } + return Semantics( + label: chatShellDismissLabel, + button: true, + excludeSemantics: true, + child: CupertinoButton( + key: const Key('chat-shell-run-dismiss'), + padding: const EdgeInsets.symmetric(horizontal: 8), + onPressed: onPressed, + child: const Icon(CupertinoIcons.xmark), + ), + ); + } +} + +/// The conversation's "Dismiss all finished commands" More menu entry. +Widget chatShellDismissAllMenuAction({required VoidCallback onPressed}) => + SegmentedOverflowAction( + key: const ValueKey('chat-shell-dismiss-all-action'), + overflowEntry: SegmentedOverflowEntry( + label: chatShellDismissAllLabel, + icon: Icons.clear_all, + onPressed: onPressed, + ), + child: const SizedBox.shrink(), + ); + +/// Dismisses [ids] for every client of the chat, then offers Undo for +/// [chatShellUndoDuration]: a Material SnackBar, or a transient Cupertino +/// notice floating over the conversation. A refusal goes to [onRefused]. +Future dismissChatShellRuns( + BuildContext context, + ChatShellRunsController controller, + List ids, { + required bool cupertino, + void Function(String refusal)? onRefused, +}) async { + if (ids.isEmpty) return; + final messenger = cupertino ? null : ScaffoldMessenger.maybeOf(context); + final overlay = Overlay.maybeOf(context, rootOverlay: true); + final refusal = await controller.dismiss(ids); + if (refusal != null) { + onRefused?.call(refusal); + return; + } + void show(String message, {VoidCallback? onUndo}) { + if (messenger != null) { + messenger.hideCurrentSnackBar(); + messenger.showSnackBar( + SnackBar( + key: const Key('chat-shell-undo-notice'), + content: Text(message), + duration: chatShellUndoDuration, + // An action would otherwise keep it until dismissed by hand. + persist: false, + action: onUndo == null + ? null + : SnackBarAction(label: chatShellUndoLabel, onPressed: onUndo), + ), + ); + } else if (overlay != null && overlay.mounted) { + _showOverlayNotice(overlay, message, onUndo); + } + } + + show( + ids.length == 1 ? 'Command dismissed' : '${ids.length} commands dismissed', + onUndo: () => unawaited(() async { + final failed = await controller.restore(ids); + if (failed != null) show("Couldn't restore: $failed"); + }()), + ); +} + +OverlayEntry? _overlayNotice; +Timer? _overlayTimer; + +void _hideOverlayNotice() { + _overlayTimer?.cancel(); + _overlayTimer = null; + final entry = _overlayNotice; + _overlayNotice = null; + if (entry != null && entry.mounted) entry.remove(); +} + +void _showOverlayNotice( + OverlayState overlay, + String message, + VoidCallback? onUndo, +) { + _hideOverlayNotice(); + final entry = OverlayEntry( + builder: (context) => Positioned( + left: 16, + right: 16, + bottom: 16, + child: SafeArea( + child: Semantics( + container: true, + explicitChildNodes: true, + liveRegion: true, + child: KeyedSubtree( + key: const Key('chat-shell-undo-notice'), + child: onUndo == null + ? CupertinoPopupSurface( + child: Padding( + padding: const EdgeInsets.all(16), + child: DefaultTextStyle.merge( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: Text(message), + ), + ), + ) + : ChatUndoBar( + message: message, + onUndo: () { + _hideOverlayNotice(); + onUndo(); + }, + ), + ), + ), + ), + ), + ); + _overlayNotice = entry; + overlay.insert(entry); + _overlayTimer = Timer(chatShellUndoDuration, _hideOverlayNotice); +} diff --git a/app/lib/features/chat/shell/chat_shell_run_card.dart b/app/lib/features/chat/shell/chat_shell_run_card.dart index f8324321..12892563 100644 --- a/app/lib/features/chat/shell/chat_shell_run_card.dart +++ b/app/lib/features/chat/shell/chat_shell_run_card.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -6,6 +8,7 @@ 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_dismiss.dart'; import 'chat_shell_output_view.dart'; import 'chat_shell_run.dart'; import 'chat_shell_runs_controller.dart'; @@ -15,7 +18,9 @@ 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. Full screen opens the same terminal over the whole window. +/// Send to agent, and Dismiss (for every client of the chat, with Undo). A +/// running command has no Dismiss: Stop it first. Full screen opens the same +/// terminal over the whole window. /// /// It listens to [controller] itself, so streamed output rebuilds only this /// card, never the transcript. @@ -126,6 +131,16 @@ class _ChatShellRunCardState extends State { ), const SizedBox(width: 8), ChatShellStatus(run: run, cupertino: cupertino), + if (!run.running) + ChatShellDismissButton( + cupertino: cupertino, + onPressed: () => unawaited( + // A refusal brings the card back with the server's reason. + dismissChatShellRuns(context, controller, [ + run.id, + ], cupertino: cupertino), + ), + ), ], ), const SizedBox(height: 12), diff --git a/app/lib/features/chat/shell/chat_shell_runs_controller.dart b/app/lib/features/chat/shell/chat_shell_runs_controller.dart index 24084f35..7e59097f 100644 --- a/app/lib/features/chat/shell/chat_shell_runs_controller.dart +++ b/app/lib/features/chat/shell/chat_shell_runs_controller.dart @@ -8,6 +8,8 @@ import 'chat_shell_run.dart'; import 'chat_shell_runs_repository.dart'; import 'chat_shell_terminals.dart'; +part 'chat_shell_runs_dismissal.dart'; + /// Where one run's "Send to agent" stands. enum ChatShellShareState { idle, sending, sent } @@ -45,6 +47,10 @@ class ChatShellRunsController extends ChangeNotifier { final Set _stopping = {}; final Map _shares = {}; final Map _errors = {}; + + /// Runs dismissed here or by another client: a readback racing the + /// dismissal does not bring their cards back. + final Set _gone = {}; bool _disposed = false; int _generation = 0; @@ -55,6 +61,12 @@ class ChatShellRunsController extends ChangeNotifier { ChatShellShareState shareState(String id) => _shares[id] ?? ChatShellShareState.idle; + /// The finished runs, oldest first: what Dismiss all finished removes. + List get finishedIds => [ + for (final run in _runs.values) + if (!run.running) run.id, + ]; + /// The last refused card action of [id], in the server's words. String? errorFor(String id) => _errors[id]; @@ -63,9 +75,11 @@ class ChatShellRunsController extends ChangeNotifier { Future refresh() async { final token = ++_generation; try { - final listed = await _repository.runs(sessionId); + final (:runs, :dismissed) = await _repository.runs(sessionId); if (_disposed || token != _generation) return; - for (final run in listed) { + dismissed.forEach(_remove); + for (final run in runs) { + if (_gone.contains(run.id)) continue; final held = _runs[run.id]; if (held != null && held.running && @@ -189,8 +203,15 @@ class ChatShellRunsController extends ChangeNotifier { final frame = envelope['chat_shell_run_event']; if (frame is! Map || frame['session_id'] != sessionId) return; final id = '${frame['run_id'] ?? ''}'; + if (frame['dismissed'] == true) { + _remove(id); + _changed(membership: true); + return; + } final record = ChatShellRun.fromJson(frame['run']); if (record != null) { + // A restored run (another client's Undo) comes back without output. + if (_gone.remove(record.id) && !record.running) unawaited(refresh()); final held = _runs[record.id]; final next = held == null ? record : held.withLifecycle(record); _runs[record.id] = next; @@ -198,9 +219,11 @@ class ChatShellRunsController extends ChangeNotifier { _stopping.remove(record.id); if (held != null && held.running) terminals.finished(next); } - _changed(membership: held == null); + // Membership also tracks finishing: Dismiss all finished depends on it. + _changed(membership: held == null || held.running != next.running); return; } + if (_gone.contains(id)) return; final held = _runs[id]; if (held == null) { // Output for a run this copy has not seen yet: read the record. diff --git a/app/lib/features/chat/shell/chat_shell_runs_dismissal.dart b/app/lib/features/chat/shell/chat_shell_runs_dismissal.dart new file mode 100644 index 00000000..64de9e53 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_runs_dismissal.dart @@ -0,0 +1,63 @@ +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. +extension ChatShellRunsDismissal on ChatShellRunsController { + /// 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. + Future dismiss(List ids) async { + final removed = [ + for (final id in ids) + if (_runs[id] case final run? when !run.running) run, + ]; + if (removed.isEmpty) return null; + for (final run in removed) { + _remove(run.id); + } + _changed(membership: true); + try { + await _repository.dismiss(sessionId, [for (final r in removed) r.id]); + return null; + } catch (error) { + if (_disposed) return null; + final reason = _reason(error); + for (final run in removed) { + _gone.remove(run.id); + _runs[run.id] = run; + _errors[run.id] = reason; + } + _changed(membership: true); + return reason; + } + } + + /// Undoes the dismissal of [ids] while the server still keeps them. + /// Returns the refusal, or null. + Future restore(List ids) async { + try { + final restored = await _repository.restore(sessionId, ids); + if (_disposed) return null; + for (final run in restored) { + _gone.remove(run.id); + final held = _runs[run.id]; + final keep = held != null && held.outputEnd >= run.outputEnd; + _runs[run.id] = keep ? held.withLifecycle(run) : run; + if (!keep) terminals.replaced(run); + } + _changed(membership: true); + return null; + } catch (error) { + return _reason(error); + } + } + + void _remove(String id) { + _gone.add(id); + _runs.remove(id); + _errors.remove(id); + _shares.remove(id); + _stopping.remove(id); + terminals.removed(id); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_runs_repository.dart b/app/lib/features/chat/shell/chat_shell_runs_repository.dart index dfb2a681..037201bd 100644 --- a/app/lib/features/chat/shell/chat_shell_runs_repository.dart +++ b/app/lib/features/chat/shell/chat_shell_runs_repository.dart @@ -14,6 +14,7 @@ class ChatShellRunsRepository { int? rows, String? data, int? after, + List? runIds, }) => { 'chat_shell_run_request': { 'session_id': sessionId, @@ -23,6 +24,7 @@ class ChatShellRunsRepository { 'rows': ?rows, 'data': ?data, 'after': ?after, + 'run_ids': ?runIds, }, }; @@ -55,11 +57,37 @@ class ChatShellRunsRepository { 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 { + /// 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 runs, Set dismissed})> runs( + String sessionId, + ) async { final reply = await gateway.call('chat_shell_runs', { 'chat_query': {'session_id': sessionId}, }); + return (runs: _records(reply), dismissed: _ids(reply)); + } + + /// Dismisses finished runs for every client of the chat; the reply names + /// the runs the server dismissed. + Future> dismiss(String sessionId, List runIds) async => + _ids( + await gateway.call( + 'chat_shell_dismiss', + _body(sessionId, runIds: runIds), + ), + ); + + /// Undoes a dismissal still inside the server's undo window; the reply is + /// the restored runs with their output tail. + Future> restore( + String sessionId, + List runIds, + ) async => _records( + await gateway.call('chat_shell_restore', _body(sessionId, runIds: runIds)), + ); + + List _records(JsonMap reply) { final value = reply['chat_shell_runs']; return [ if (value is List) @@ -67,6 +95,14 @@ class ChatShellRunsRepository { ]; } + Set _ids(JsonMap reply) { + final value = reply['chat_shell_dismissed']; + return { + if (value is List) + for (final id in value) '$id', + }; + } + /// One run with the whole output the server retained and its plain-text /// rendering, or only the output from absolute byte [after] on. Future output( diff --git a/app/lib/features/chat/shell/chat_shell_terminals.dart b/app/lib/features/chat/shell/chat_shell_terminals.dart index 54b6bb8e..2201b466 100644 --- a/app/lib/features/chat/shell/chat_shell_terminals.dart +++ b/app/lib/features/chat/shell/chat_shell_terminals.dart @@ -54,6 +54,14 @@ class ChatShellTerminals { void appended(ChatShellRun run, String text, int offset, int end) => _sessions[run.id]?.append(run, text, offset, end); + /// [runId]'s card was dismissed: drop its emulator. + void removed(String runId) { + _resizes.remove(runId)?.cancel(); + _inputs.remove(runId); + _sentSizes.remove(runId); + _sessions.remove(runId); + } + /// [run] ended: draw its final output read-only. void finished(ChatShellRun run) { _resizes.remove(run.id)?.cancel(); diff --git a/app/notes/chat-shell-commands.md b/app/notes/chat-shell-commands.md index d276a991..6bdb51f8 100644 --- a/app/notes/chat-shell-commands.md +++ b/app/notes/chat-shell-commands.md @@ -130,6 +130,58 @@ change, and `{session_id, run_id, output, offset, end}` for output chunks. - The process group is killed on Stop, on server shutdown and after the command exits, so a run cannot leave an orphan holding the server's pipe. +## Dismissing commands + +- A finished card (exited, stopped, failed, interrupted) has a Dismiss + button: a close icon with the tooltip (Material) or semantics label + (Cupertino) "Dismiss". The card has no menu, so there is no menu entry. +- A running card has no Dismiss. Stop it first; once it ends, Dismiss + appears. This was chosen over "Stop and dismiss" because a command that + ignores SIGINT keeps running for the grace period, and hiding a live + process's card would be confusing. +- The chat's More menu has "Dismiss all finished commands" when at least one + run has finished. It dismisses every finished run and leaves running ones. +- Dismissal is per chat, for every client (not per device). The card goes at + once. A refusal brings the card back with the server's reason. +- Undo: a 5 s SnackBar (Material) or a transient notice over the + conversation (Cupertino, `ChatUndoBar` in the root overlay) offers Undo. + The Cupertino notice briefly covers the composer. +- Server design: dismiss-then-restore within a window, then purge. + `chat_shell_dismiss {session_id, run_ids}` sets `dismissed_at` on finished + runs and pushes `chat_shell_run_event {dismissed: true}` to every watcher. + `chat_shell_restore {session_id, run_ids}` clears it within + `ChatShellRunUndoWindow` (30 s, longer than the 5 s notice). The reply + carries the runs, and watchers get lifecycle frames. A client that held no + copy reads the list again for the output. After the window the server + purges the run's command, output, output text and error (an `AfterFunc`, + plus on every server start). Only a tombstone row remains. +- Readback: `chat_shell_runs` and `chat_shell_run_output` exclude dismissed + runs. `chat_shell_runs` lists tombstone ids in `chat_shell_dismissed`, so a + client that missed the event drops those cards on its next refresh. + Tombstones age out with the 50-run history prune. +- Files: `internal/protocol/chat_shell_dismiss.go`, + `internal/pipeline/chat_shell_dismiss.go`, + `internal/server/chat_shell_dismiss.go`, + `lib/features/chat/shell/chat_shell_dismiss.dart` (button, menu entry, + Undo notice) and `chat_shell_runs_dismissal.dart` (controller part). +- Tests: `internal/pipeline/chat_shell_dismiss_test.go` covers dismiss, + readback, restore, purge and tombstones. + `internal/server/chat_shell_dismiss_test.go` covers the websocket dismiss + to two watchers, refusing a running or empty request, readback with + tombstones, refusing output for a dismissed run, Undo, and purge after the + window and on restart. `test/features/chat/shell/chat_shell_dismiss_test.dart` + covers the button, Undo and notice expiry (both hosts), a refused dismiss, + the menu entry's absence and dismiss-all, another client's dismissal and + restore, and tombstone readback. +- Verification (2026-11-09): `go test ./internal/protocol ./internal/pipeline + ./internal/server` all ok. `tool/memwatch/full.sh test/features/chat` + gives `PASS: 1146 passed, 0 failed`. `tool/analyze.sh` is clean. Real + Chrome captures (`tool/capture`, `chats=1&msgs=2&shell=1`) covered Material + light 880x1000 and Cupertino dark 560x1000: cards with Dismiss, the Undo + notice, the restored card, the More menu entry, dismiss-all with its + notice, and (Cupertino) the notice gone after 5 s. The PNGs were inspected. + A live server and browser session was not exercised end to end. + ## Files - Server: `internal/protocol/chat_shell_run.go`, diff --git a/app/test/features/chat/shell/chat_shell_dismiss_test.dart b/app/test/features/chat/shell/chat_shell_dismiss_test.dart new file mode 100644 index 00000000..4d3c1e33 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_dismiss_test.dart @@ -0,0 +1,180 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_runs_controller.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.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'); + final dismiss = find.byKey(const Key('chat-shell-run-dismiss')); + final notice = find.byKey(const Key('chat-shell-undo-notice')); + + JsonMap finished(String id, {String command = 'true'}) => shellRecord( + id, + command: command, + status: 'exited', + exitCode: 0, + output: 'out $id\n', + durationMs: 50, + ); + + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$host: Dismiss removes a finished card and Undo restores it', ( + tester, + ) async { + gateway.runs = [finished('run_done'), shellRecord('run_live')]; + await tester.pumpWidget(shellThread(gateway, cupertino: cupertino)); + await tester.pump(); + + expect(card(), findsNWidgets(2)); + // Only the finished card offers Dismiss; a running one must stop first. + expect(dismiss, findsOneWidget); + expect( + cupertino + ? find.bySemanticsLabel('Dismiss') + : find.byTooltip('Dismiss'), + findsOneWidget, + ); + + await tester.tap(dismiss); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(gateway.bodies('chat_shell_dismiss').single['run_ids'], [ + 'run_done', + ]); + expect(card(), findsOneWidget); + expect(find.text('\$ true'), findsNothing); + expect(notice, findsOneWidget); + expect(find.text('Command dismissed'), findsOneWidget); + + await tester.tap(find.text('Undo')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(gateway.bodies('chat_shell_restore').single['run_ids'], [ + 'run_done', + ]); + expect(card(), findsNWidgets(2)); + expect(find.text('\$ true'), findsOneWidget); + }); + + testWidgets('$host: the Undo notice goes away after five seconds', ( + tester, + ) async { + gateway.runs = [finished('run_done')]; + await tester.pumpWidget(shellThread(gateway, cupertino: cupertino)); + await tester.pump(); + await tester.tap(dismiss); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(notice, findsOneWidget); + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + expect(notice, findsNothing); + expect(card(), findsNothing); + expect(gateway.bodies('chat_shell_restore'), isEmpty); + }); + } + + testWidgets('a refused dismissal brings the card back with the reason', ( + tester, + ) async { + gateway.runs = [finished('run_done')]; + gateway.dismissRefusal = 'the store is read-only'; + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.tap(dismiss); + await tester.pump(); + expect(card(), findsOneWidget); + expect(find.byKey(const Key('chat-shell-run-error')), findsOneWidget); + expect(find.textContaining('the store is read-only'), findsOneWidget); + expect(notice, findsNothing); + }); + + testWidgets('the More menu has no Dismiss all without a finished run', ( + tester, + ) async { + gateway.runs = [shellRecord('run_live')]; + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.tap(find.byKey(segmentedMoreKey).hitTestable().first); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.text('Run command…'), findsOneWidget); + expect(find.text('Dismiss all finished commands'), findsNothing); + }); + + testWidgets('Dismiss all finished commands leaves running ones', ( + tester, + ) async { + gateway.runs = [shellRecord('run_live'), shellRecord('run_a')]; + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + // Finishing runs offers the entry. + gateway.runs = [ + finished('run_a'), + finished('run_b', command: 'ls'), + shellRecord('run_live'), + ]; + gateway.emitRun(finished('run_a')); + gateway.emitRun(finished('run_b', command: 'ls')); + await tester.pump(); + await tester.tap(find.byKey(segmentedMoreKey).hitTestable().first); + await tester.pump(const Duration(milliseconds: 500)); + await tester.tap(find.text('Dismiss all finished commands')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + + expect(gateway.bodies('chat_shell_dismiss').single['run_ids'], [ + 'run_a', + 'run_b', + ]); + expect(card(), findsOneWidget); + expect(find.text('2 commands dismissed'), findsOneWidget); + // Let the SnackBar finish entering. + await tester.pump(const Duration(milliseconds: 500)); + await tester.tap(find.text('Undo')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(card(), findsNWidgets(3)); + }); + + testWidgets('another client dismissing a run removes its card here', ( + tester, + ) async { + gateway.runs = [finished('run_done')]; + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + expect(card(), findsOneWidget); + gateway.emitDismissed('run_done'); + await tester.pump(); + expect(card(), findsNothing); + // Its Undo there restores it here too, output read back. + gateway.emitRun(finished('run_done')); + await tester.pump(); + await tester.pump(); + expect(card(), findsOneWidget); + expect(gateway.calls.where((c) => c.type == 'chat_shell_runs').length, 2); + }); + + test('a readback drops runs dismissed while this copy was away', () async { + gateway.runs = [finished('run_a'), finished('run_b')]; + final controller = ChatShellRunsController(gateway, 's'); + addTearDown(controller.dispose); + await pumpEventQueue(); + expect(controller.runs.map((r) => r.id), ['run_a', 'run_b']); + + gateway.runs = [finished('run_b')]; + gateway.dismissed = ['run_a']; + await controller.refresh(); + expect(controller.runs.map((r) => r.id), ['run_b']); + expect(controller.finishedIds, ['run_b']); + }); +} diff --git a/app/test/features/chat/shell/chat_shell_fixtures.dart b/app/test/features/chat/shell/chat_shell_fixtures.dart index 439b8545..0b37fb35 100644 --- a/app/test/features/chat/shell/chat_shell_fixtures.dart +++ b/app/test/features/chat/shell/chat_shell_fixtures.dart @@ -18,6 +18,13 @@ class ShellGateway implements ApiGateway { List runs = const []; String? refusal; + /// Tombstone ids the `chat_shell_runs` readback reports. + List dismissed = const []; + + /// The refusal of `chat_shell_dismiss` / `chat_shell_restore`, when set. + String? dismissRefusal; + String? restoreRefusal; + /// The reply to a `chat_shell_run_output` that resumes from an offset. JsonMap? resumeReply; int _serial = 0; @@ -42,7 +49,19 @@ class ShellGateway implements ApiGateway { case 'chat_messages': return chatPage(const []); case 'chat_shell_runs': - return {'chat_shell_runs': runs}; + return {'chat_shell_runs': runs, 'chat_shell_dismissed': dismissed}; + case 'chat_shell_dismiss': + if (dismissRefusal != null) throw StateError(dismissRefusal!); + return {'chat_shell_dismissed': body['run_ids']}; + case 'chat_shell_restore': + if (restoreRefusal != null) throw StateError(restoreRefusal!); + final ids = (body['run_ids'] as List).toSet(); + return { + 'chat_shell_runs': [ + for (final run in runs) + if (ids.contains(run['id'])) run, + ], + }; case 'chat_shell_run': if (refusal != null) throw StateError(refusal!); return { @@ -82,6 +101,15 @@ class ShellGateway implements ApiGateway { }, }); + void emitDismissed(String id) => _frames.add({ + 'type': 'chat_shell_run_event', + 'chat_shell_run_event': { + 'session_id': 's', + 'run_id': id, + 'dismissed': true, + }, + }); + void close() => _frames.close(); } diff --git a/app/tool/perf/chat_shell_fixture.dart b/app/tool/perf/chat_shell_fixture.dart index e066045b..9d88d9e1 100644 --- a/app/tool/perf/chat_shell_fixture.dart +++ b/app/tool/perf/chat_shell_fixture.dart @@ -2,7 +2,7 @@ // `?chats=N`): every fixture chat lists four recorded terminal runs // (succeeded, failed, stopped and an interactive login still waiting for a // token), and chat_shell_run/stop/share/input answer as the server does, with -// the frames that follow. The login prompt hides what is typed, as a real +// the frames that follow; chat_shell_dismiss/restore hide and bring back runs. The login prompt hides what is typed, as a real // terminal's password prompt does, and finishes on Enter. import 'dart:convert'; @@ -12,11 +12,18 @@ bool _enabled = false; DateTime _base = DateTime.now(); int _loginEnd = utf8.encode(_loginPrompt).length; int _tokenLength = 0; +final Set _dismissed = {}; + +List _runIds(Object? body) => [ + if (body is Map && body['run_ids'] is List) + for (final id in body['run_ids'] as List) '$id', +]; void configureChatShellFixture(Map params) { _enabled = params['shell'] == '1'; _base = DateTime.now().subtract(const Duration(minutes: 3)); _loginEnd = utf8.encode(_loginPrompt).length; + _dismissed.clear(); } const String _loginPrompt = @@ -116,7 +123,30 @@ JsonMap? chatShellReply(JsonMap request) { return { 'id': id, 'type': 'chat_shell_runs', - 'chat_shell_runs': _runs(session), + 'chat_shell_runs': [ + for (final run in _runs(session)) + if (!_dismissed.contains(run['id'])) run, + ], + 'chat_shell_dismissed': _dismissed.toList(), + }; + case 'chat_shell_dismiss': + final ids = _runIds(body); + _dismissed.addAll(ids); + return { + 'id': id, + 'type': 'chat_shell_dismiss', + 'chat_shell_dismissed': ids, + }; + case 'chat_shell_restore': + final ids = _runIds(body).toSet(); + _dismissed.removeAll(ids); + return { + 'id': id, + 'type': 'chat_shell_restore', + 'chat_shell_runs': [ + for (final run in _runs(session)) + if (ids.contains(run['id'])) run, + ], }; case 'chat_shell_run': return { @@ -160,6 +190,17 @@ List chatShellFollowUps(JsonMap request) { 'chat_shell_run_event': {'session_id': session, ...body}, }; switch ('${request['type']}') { + case 'chat_shell_dismiss': + return [ + for (final runId in _runIds(request['chat_shell_run_request'])) + frame({'run_id': runId, 'dismissed': true}), + ]; + case 'chat_shell_restore': + final ids = _runIds(request['chat_shell_run_request']).toSet(); + return [ + for (final run in _runs(session)) + if (ids.contains(run['id'])) frame({'run_id': run['id'], 'run': run}), + ]; case 'chat_shell_run': const text = 'hello from the fixture shell\n'; final body = request['chat_shell_run_request'];