The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(desktop): allow closing panes after session stop failures (#761)
Deef54cfef6ea82
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex a6915eb79..687e22407 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -289,10 +289,12 @@ waiting-for-input, draft, or unknown sessions share one confirmation for the whotheir names, activity, and the number of sessions that will stop. Its only choices are Canceland Stop; Cancel is the default. Stop saves and stops every reviewed session before the tabcloses. Idle-only closes retain the daemon's activity guard; newly active work gets one review-of the remaining sessions. Failures keep the view and identify confirmed stops separately-from uncertain ones. Previously queued daemon close-plans remain compatible. Layout cleanup, moving panes, switching tabs, and sign-out retain their view-only behavior. A failed save-or unconfirmed close keeps the pane. Older daemons retain their existing behavior until updated.+of the remaining sessions. Failures identify confirmed stops separately from uncertain ones+and default to Keep open. Close pane / Close Tab dismisses the captured views through the+normal recently-closed history path without another stop request; unconfirmed sessions may+still be running, and their views in other tabs remain open. Previously queued daemon close+plans remain compatible. Layout cleanup, moving panes, switching tabs, and sign-out retain+their view-only behavior. Older daemons retain their existing behavior until updated.`HarnessMonitor` supplies the global running-harness count without process samplingin the footer. Clicking it opens the reusable `autonomous/harness-monitor` DSH tabdiff --git a/desktop/integration_test/session_close_native_test.dart b/desktop/integration_test/session_close_native_test.dartnew file mode 100644index 000000000..2c243a340--- /dev/null+++ b/desktop/integration_test/session_close_native_test.dart@@ -0,0 +1,22 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/test_run.dart';+import 'package:integration_test/integration_test.dart';+import 'package:window_manager/window_manager.dart';++import '../test/session_close_dialog_test.dart' as dialog;+import '../test/session_close_test.dart' as close;++void main() {+ if (!kUnderTest) {+ throw StateError('Session close fixtures require FLUTTER_TEST=1');+ }+ IntegrationTestWidgetsFlutterBinding.ensureInitialized().framePolicy =+ LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;+ setUpAll(() async {+ await windowManager.ensureInitialized();+ await windowManager.show();+ await windowManager.focus();+ });+ close.main();+ dialog.main();+}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 222091690..b56c0c13d 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -2627,28 +2627,41 @@ class _SwarmScreenState extends State<SwarmScreen> {return result;}- Future<bool> inspectFrom(int start) async {+ Future<bool> closeAfterError(String error) async {+ if (await choose(error: error) != 'close_view' || !mounted) return false;+ // This only dismisses the captured views. It neither retries Stop nor+ // treats a lost reply as proof that the session stopped. A replaced+ // session must not inherit a choice made for the old one.+ return targets.every((target) {+ final current = app.stateOf(target.$1)?.agents+ .where((agent) => agent.id == target.$2.id)+ .firstOrNull;+ return current == null ||+ (current.createdAt == target.$2.createdAt &&+ current.sessionId == target.$2.sessionId);+ });+ }++ Future<String?> inspectFrom(int start) async {for (var i = start; i < requests.length; i++) {- if (!mounted) return false;+ if (!mounted) return null;final state = await requests[i]('inspect');- if (!mounted) return false;+ if (!mounted) return null;if (state['error'] != null) {- await choose(- error:- state['detail'] as String? ??- 'Could not check ${targets[i].$2.displayName}. Nothing else will be stopped.',- );- return false;+ return state['detail'] as String? ??+ 'Could not check ${targets[i].$2.displayName}. Nothing else will be stopped.';}activities[i] = state['activity'] as String? ?? 'unknown';}- return true;+ return null;}// Inspect the whole captured set before one decision, or any stop. Stop// approves every listed session, including idle ones that start work while// the prompt is open; an unprompted close keeps the daemon's idle guard.- if (!await inspectFrom(0)) return false;+ final inspectionError = await inspectFrom(0);+ if (!mounted) return false;+ if (inspectionError != null) return closeAfterError(inspectionError);var stopNow = activities.any((activity) => activity != 'idle');if (stopNow && await choose() != 'now') return false;for (var i = 0; i < requests.length; i++) {@@ -2659,7 +2672,9 @@ class _SwarmScreenState extends State<SwarmScreen> {// session together, and disclose any sessions that already stopped.if (result['error'] == 'SESSION_NOT_IDLE') {activities[i] = result['activity'] as String? ?? 'unknown';- if (!await inspectFrom(i + 1)) return false;+ final inspectionError = await inspectFrom(i + 1);+ if (!mounted) return false;+ if (inspectionError != null) return closeAfterError(inspectionError);if (await choose() != 'now') return false;stopNow = true;result = await requests[i]('now');@@ -2667,12 +2682,10 @@ class _SwarmScreenState extends State<SwarmScreen> {if (!mounted) return false;if (result['closed'] != true && result['deferred'] != true) {activities[i] = 'unconfirmed';- await choose(- error:- result['detail'] as String? ??+ return closeAfterError(+ result['detail'] as String? ??'Could not confirm that ${targets[i].$2.displayName} stopped. Its saved history is kept.',);- return false;}activities[i] = result['closed'] == true ? 'stopped' : 'deferred';}diff --git a/desktop/lib/widgets/session_close_dialog.dart b/desktop/lib/widgets/session_close_dialog.dartindex 74e25833e..c94b15873 100644--- a/desktop/lib/widgets/session_close_dialog.dart+++ b/desktop/lib/widgets/session_close_dialog.dart@@ -125,7 +125,9 @@ class _SessionClosePromptState extends State<_SessionClosePrompt> {Text(widget.error == null? 'Stopping ${count == 1 ? 'this session' : 'all $count sessions'} will close $scope. History will be saved.'- : '${widget.tabName == null ? 'This pane' : 'The tab'} stays open.',+ : widget.tabName == null+ ? 'You can close this pane. The session may still be running.'+ : 'You can close this tab. Some sessions may still be running.',style: DesktopChrome.text(size: 13),),const SizedBox(height: DesktopChrome.groupGap),@@ -165,7 +167,7 @@ class _SessionClosePromptState extends State<_SessionClosePrompt> {TextButton(focusNode: _cancel,onPressed: _choose,- child: Text(widget.error == null ? 'Cancel' : 'OK'),+ child: Text(widget.error == null ? 'Cancel' : 'Keep open'),),if (widget.error == null) ...[FilledButton(@@ -174,7 +176,14 @@ class _SessionClosePromptState extends State<_SessionClosePrompt> {onPressed: () => _choose('now'),child: const Text('Stop'),),- ],+ ] else+ FilledButton(+ key: const Key('session-close-view'),+ onPressed: () => _choose('close_view'),+ child: Text(+ widget.tabName == null ? 'Close pane' : 'Close Tab',+ ),+ ),],),),diff --git a/desktop/test/session_close_dialog_test.dart b/desktop/test/session_close_dialog_test.dartindex bee1b5706..9e4ec16ef 100644--- a/desktop/test/session_close_dialog_test.dart+++ b/desktop/test/session_close_dialog_test.dart@@ -23,119 +23,136 @@ void main() {for (final brightness in Brightness.values) {for (final scale in [1.0, 2.0]) {for (final tab in [false, true]) {- testWidgets(- '${brightness.name} ${tab ? 'tab' : 'pane'} close prompt at ${scale}x',- (tester) async {- final previousBrightness = grid.AppTheme.brightness.value;- grid.AppTheme.brightness.value = brightness;- addTearDown(- () => grid.AppTheme.brightness.value = previousBrightness,- );- tester.view.devicePixelRatio = 1;- tester.view.physicalSize = scale == 1- ? const Size(800, 500)- : const Size(360, 320);- addTearDown(tester.view.resetPhysicalSize);- addTearDown(tester.view.resetDevicePixelRatio);- final picture = GlobalKey();- var dismissed = false;- await tester.pumpWidget(- MaterialApp(- debugShowCheckedModeBanner: false,- theme: grid.buildAppTheme(brightness: brightness),- builder: (context, child) => MediaQuery(- data: MediaQuery.of(context)- .copyWith(textScaler: TextScaler.linear(scale)),- child: RepaintBoundary(key: picture, child: child!),- ),- home: Builder(- builder: (context) => Scaffold(- body: Center(- child: TextButton(- onPressed: () async {- final result = await showSessionCloseDialog(context, [- const SessionCloseItem(- name: 'Fix authentication',- activity: 'working',- ),- if (tab) ...[- const SessionCloseItem(- name: 'Investigate the intermittent checkout failure on the staging machine',- activity: 'working',- ),- const SessionCloseItem(- name: 'Update documentation',- activity: 'idle',- ),- const SessionCloseItem(- name: 'Review changes',- activity: 'idle',- ),- const SessionCloseItem(- name: 'Check release notes',- activity: 'idle',- ),- ],- ], tabName: tab ? 'Release' : null);- expect(result, isNull);- dismissed = true;- },- child: const Text('Open'),+ for (final failed in [false, true]) {+ const failure =+ 'WebSocket was closed before the connection was established';+ testWidgets(+ '${brightness.name} ${tab ? 'tab' : 'pane'} ${failed ? 'failed' : 'working'} close prompt at ${scale}x',+ (tester) async {+ final previousBrightness = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(+ () => grid.AppTheme.brightness.value = previousBrightness,+ );+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = scale == 1+ ? const Size(800, 500)+ : const Size(360, 320);+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ final picture = GlobalKey();+ var dismissed = false;+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(scale)),+ child: RepaintBoundary(key: picture, child: child!),+ ),+ home: Builder(+ builder: (context) => Scaffold(+ body: Center(+ child: TextButton(+ onPressed: () async {+ final result = await showSessionCloseDialog(+ context,+ [+ const SessionCloseItem(+ name: 'Fix authentication',+ activity: 'working',+ ),+ if (tab) ...[+ const SessionCloseItem(+ name: 'Investigate the intermittent checkout failure on the staging machine',+ activity: 'working',+ ),+ const SessionCloseItem(+ name: 'Update documentation',+ activity: 'idle',+ ),+ const SessionCloseItem(+ name: 'Review changes',+ activity: 'idle',+ ),+ const SessionCloseItem(+ name: 'Check release notes',+ activity: 'idle',+ ),+ ],+ ],+ tabName: tab ? 'Release' : null,+ error: failed ? failure : null,+ );+ expect(result, isNull);+ dismissed = true;+ },+ child: const Text('Open'),+ ),),),),),- ),- );- await tester.tap(find.text('Open'));- await tester.pumpAndSettle();- final message = find.text(- tab- ? '2 sessions are still working.'- : '1 session is still working.',- );- final cancel = find.widgetWithText(TextButton, 'Cancel');- final close = find.widgetWithText(FilledButton, 'Stop');- expect(message, findsOneWidget);- expect(find.byType(FilledButton), findsOneWidget);- expect(find.widgetWithText(TextButton, 'Cancel'), findsOneWidget);- expect(- tester.widget<TextButton>(cancel).focusNode!.hasFocus,- isTrue,- );- // Enlarged text can scroll; the visible body must stay above actions.- expect(- tester.getBottomLeft(find.byType(DesktopPromptScrollBody)).dy,- lessThan(tester.getTopLeft(cancel).dy),- );- expect(- tester.getBottomRight(close).dy,- lessThan(tester.view.physicalSize.height),- );- expect(tester.takeException(), isNull);+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ final message = find.text(+ failed+ ? failure+ : tab+ ? '2 sessions are still working.'+ : '1 session is still working.',+ );+ final cancel = find.widgetWithText(+ TextButton,+ failed ? 'Keep open' : 'Cancel',+ );+ final close = find.widgetWithText(+ FilledButton,+ failed ? (tab ? 'Close Tab' : 'Close pane') : 'Stop',+ );+ expect(message, findsOneWidget);+ expect(find.byType(FilledButton), findsOneWidget);+ expect(cancel, findsOneWidget);+ expect(+ tester.widget<TextButton>(cancel).focusNode!.hasFocus,+ isTrue,+ );+ // Enlarged text can scroll; the visible body must stay above actions.+ expect(+ tester.getBottomLeft(find.byType(DesktopPromptScrollBody)).dy,+ lessThan(tester.getTopLeft(cancel).dy),+ );+ expect(+ tester.getBottomRight(close).dy,+ lessThan(tester.view.physicalSize.height),+ );+ expect(tester.takeException(), isNull);- if (renderDir != null) {- await tester.runAsync(() async {- final boundary =- picture.currentContext!.findRenderObject()!- as RenderRepaintBoundary;- final image = await boundary.toImage(pixelRatio: 2);- final data = await image.toByteData(- format: ui.ImageByteFormat.png,- );- Directory(renderDir).createSync(recursive: true);- await File(- '$renderDir/${brightness.name}-${tab ? 'tab' : 'pane'}-${scale}x.png',- ).writeAsBytes(data!.buffer.asUint8List());- image.dispose();- });- }- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pumpAndSettle();- expect(dismissed, isTrue);- expect(message, findsNothing);- },- );+ if (renderDir != null) {+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 2);+ final data = await image.toByteData(+ format: ui.ImageByteFormat.png,+ );+ Directory(renderDir).createSync(recursive: true);+ await File(+ '$renderDir/${brightness.name}-${tab ? 'tab' : 'pane'}-${failed ? 'failed' : 'working'}-${scale}x.png',+ ).writeAsBytes(data!.buffer.asUint8List());+ image.dispose();+ });+ }+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(dismissed, isTrue);+ expect(message, findsNothing);+ },+ );+ }}}}diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dartindex 4cdcb63a1..ff6fc2073 100644--- a/desktop/test/session_close_test.dart+++ b/desktop/test/session_close_test.dart@@ -68,11 +68,11 @@ class _CloseConnection extends WsConn {void main() {late AppNotifier app;late _CloseConnection connection;- Agent agent(String id, {bool started = true}) => Agent(+ Agent agent(String id, {bool started = true, String? sessionId}) => Agent(id: id,name: 'Work $id',engine: 'codex',- sessionId: started ? 'conversation-$id' : null,+ sessionId: started ? sessionId ?? 'conversation-$id' : null,createdAt: DateTime.utc(2026, 9, 30, 12),closeSupported: true,terminalAvailable: true,@@ -241,7 +241,7 @@ void main() {unawaited(app.requestClosePane(pane.id));await tester.pumpAndSettle();expect(find.text('Not enough free disk space.'), findsOneWidget);- await tester.tap(find.text('OK'));+ await tester.tap(find.text('Keep open'));await tester.pumpAndSettle();expect(app.panes, [pane]);expect(app.closedHistory, isEmpty);@@ -250,6 +250,117 @@ void main() {await tester.pumpWidget(const SizedBox());});+ for (final closeTab in [false, true]) {+ for (final failedMode in ['inspect', 'idle', 'now']) {+ testWidgets(+ '$failedMode failure can dismiss the ${closeTab ? 'tab' : 'pane'} without stopping again',+ (tester) async {+ const error =+ 'WebSocket was closed before the connection was established';+ connection.failures[failedMode] = {+ 'error': 'BACKEND_DOWN',+ 'detail': error,+ };+ if (failedMode == 'now') connection.activities['a0'] = 'working';+ final pane = app.adoptSessionForTest(terminal('a0', []));+ final sibling = app.adoptSessionForTest(terminal('a1', []));+ final original = app.activeSwarm;+ app.newSwarm();+ final other = app.activeSwarm;+ other.panes.add(pane);+ other.focusedPaneId = pane.id;+ app.selectSwarm(original.id);+ await mount(tester, app);+ unawaited(+ closeTab+ ? app.requestCloseSwarm(original.id)+ : app.requestClosePane(pane.id),+ );+ await tester.pumpAndSettle();+ if (failedMode == 'now') {+ await tester.tap(find.text('Stop'));+ await tester.pumpAndSettle();+ }+ expect(find.text(error), findsOneWidget);+ expect(+ tester+ .widget<TextButton>(+ find.widgetWithText(TextButton, 'Keep open'),+ )+ .focusNode!+ .hasFocus,+ isTrue,+ );+ final sent = List.of(connection.closes);+ await tester.tap(find.byKey(const Key('session-close-view')));+ await tester.pumpAndSettle();+ expect(find.byType(Dialog), findsNothing);+ expect(connection.closes, sent);+ expect(+ app.stateOf('m')!.agents.every((agent) => !agent.isStopped),+ isTrue,+ );+ expect(other.panes, [pane]);+ expect(pane.session, isNotNull);+ if (closeTab) {+ expect(app.swarms, isNot(contains(original)));+ } else {+ expect(original.panes, [sibling]);+ }+ expect(app.closedHistory, hasLength(1));+ expect(app.canReopenLastClosed, isTrue);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ },+ );+ }+ }++ testWidgets('a stale pane closes and can reopen from History while offline', (+ tester,+ ) async {+ connection.failures['idle'] = {'error': 'CLOSE_UNCONFIRMED'};+ final pane = app.adoptSessionForTest(terminal('a0', []));+ final original = app.activeSwarm;+ await mount(tester, app);+ unawaited(app.requestClosePane(pane.id));+ await tester.pumpAndSettle();+ app.stateOf('m')!+ ..connectionStatus = ConnectionStatus.disconnected+ ..nodeOnline = false;+ await tester.tap(find.text('Close pane'));+ await tester.pumpAndSettle();+ expect(modes(), ['inspect', 'idle']);+ expect(app.allPanes, isEmpty);+ expect(pane.session, isNull);+ expect(app.canReopenLastClosed, isTrue);+ app.reopenClosedSwarm();+ // An offline terminal keeps its loading indicator animated.+ await tester.pump(const Duration(milliseconds: 100));+ expect(app.activeSwarm.id, original.id);+ expect(app.panes.single.agentId, 'a0');+ expect(app.stateOf('m')!.agents.first.isStopped, isFalse);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets('a replaced session cannot inherit the failure dialog close', (+ tester,+ ) async {+ connection.failures['idle'] = {'error': 'CLOSE_UNCONFIRMED'};+ final pane = app.adoptSessionForTest(terminal('a0', []));+ await mount(tester, app);+ unawaited(app.requestClosePane(pane.id));+ await tester.pumpAndSettle();+ app.stateOf('m')!.agents[0] = agent('a0', sessionId: 'replacement');+ await tester.tap(find.text('Close pane'));+ await tester.pumpAndSettle();+ expect(app.panes, [pane]);+ expect(app.closedHistory, isEmpty);+ expect(modes(), ['inspect', 'idle']);+ await tester.pumpWidget(const SizedBox());+ });+for (final closeTab in [false, true]) {testWidgets('a session that starts working can still close its ${closeTab ? 'tab' : 'pane'} after review',@@ -446,7 +557,7 @@ void main() {expect(find.text('Could not reach the machine.'), findsOneWidget);expect(find.widgetWithText(FilledButton, 'Stop'), findsNothing);expect(modes(), ['inspect', 'inspect']);- await tester.tap(find.text('OK'));+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pumpAndSettle();expect(app.panes, hasLength(2));expect(app.stateOf('m')!.agents.any((agent) => agent.isStopped), isFalse);@@ -472,9 +583,12 @@ void main() {expect(find.text('Not enough free disk space.'), findsOneWidget);expect(find.text('Stopped'), findsOneWidget);expect(find.text('Stop not confirmed'), findsOneWidget);- expect(find.text('The tab stays open.'), findsOneWidget);+ expect(+ find.text('You can close this tab. Some sessions may still be running.'),+ findsOneWidget,+ );expect(find.widgetWithText(FilledButton, 'Stop'), findsNothing);- await tester.tap(find.text('OK'));+ await tester.tap(find.text('Keep open'));await tester.pumpAndSettle();expect(app.swarms, contains(tab));expect(tab.panes, hasLength(2));@@ -490,6 +604,45 @@ void main() {await tester.pumpWidget(const SizedBox());});+ testWidgets(+ 'a partially stopped tab can close without stopping later sessions',+ (tester) async {+ app.stateOf('m')!.agents.add(agent('a2'));+ connection.activities['a0'] = 'working';+ connection.targetedFailures[('a1', 'now')] = {+ 'error': 'CLOSE_UNCONFIRMED',+ };+ for (final id in ['a0', 'a1', 'a2']) {+ app.adoptSessionForTest(terminal(id, []));+ }+ final tab = app.activeSwarm;+ await mount(tester, app);+ unawaited(app.requestCloseSwarm(tab.id));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Stop'));+ await tester.pumpAndSettle();+ expect(find.text('Stopped'), findsOneWidget);+ expect(find.text('Stop not confirmed'), findsOneWidget);+ final sent = List.of(connection.closes);+ await tester.tap(find.text('Close Tab'));+ await tester.pumpAndSettle();+ expect(connection.closes, sent);+ expect(app.swarms, isNot(contains(tab)));+ expect(app.allPanes, isEmpty);+ expect(+ app+ .stateOf('m')!+ .agents+ .where((agent) => agent.isStopped)+ .map((agent) => agent.id),+ ['a0'],+ );+ expect(app.closedHistory, hasLength(1));+ expect(app.canReopenLastClosed, isTrue);+ await tester.pumpWidget(const SizedBox());+ },+ );+testWidgets('new work during an idle close reviews all remaining sessions once',(tester) async {diff --git a/docs/images/session-close-recovery.png b/docs/images/session-close-recovery.pngnew file mode 100644index 000000000..1be0df548Binary files /dev/null and b/docs/images/session-close-recovery.png differ