Skip to content

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.

desktop: Stop closes a harness that bound its conversation after the review (#1255)

Dee004549d1d1f2
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 736b2f594..3fb46323d 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -346,8 +346,11 @@ closes. Idle-only closes retain the daemon's activity guard; newly active work g
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
+still be running, and their views in other tabs remain open. A session reviewed before its
+engine bound a conversation (Codex's first seconds) that has bound one since is the same session
+(`Agent.continuesSession`): its Stop names the reviewed identity, no conversation, and the daemon
+decides (CLI `closeAgentService.ts` `matches`); another conversation once one was bound is a
+change. 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 sampling
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 8bcde7efb..fce91c1c8 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -472,6 +472,24 @@ class Agent {
bool get isStopped => status == 'stopped';
+ /// Whether this is still the session a close reviewed as [reviewed]: the
+ /// same registration in the same conversation, or one that had no
+ /// conversation when it was reviewed and has bound its first since.
+ ///
+ /// Codex binds none for its first seconds, so a pane closed just after it
+ /// started was reviewed unbound and had bound one by the time the person
+ /// pressed Stop. Read as a change, that Stop was answered "The session
+ /// changed. Check it before closing." and the harness kept running (clean
+ /// macOS VM, Desktop 1.2.65, Codex 0.162.1, 2026-10-12). The close still
+ /// names the identity it reviewed, no conversation, and the daemon accepts
+ /// that only from a harness still starting — not one resumed, typed into a
+ /// terminal or older than a minute (cli `closeAgentService.ts` `matches`).
+ /// A different conversation once one was bound is always a change.
+ bool continuesSession(Agent reviewed) =>
+ createdAt == reviewed.createdAt &&
+ (sessionId == reviewed.sessionId ||
+ (reviewed.sessionId?.isEmpty ?? true));
+
/// Exact saved-conversation resume is currently implemented for these engines.
bool get canResumeConversation =>
(engine == 'claude' || engine == 'codex') &&
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index d19291aa9..0180fbb2c 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -2653,16 +2653,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
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.
+ // session must not inherit a choice made for the old one; one that
+ // only bound its first conversation since the review is not replaced.
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);
+ return current == null || current.continuesSession(target.$2);
});
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 32592ae63..c9bdab1b3 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2567,10 +2567,12 @@ class AppNotifier extends ChangeNotifier {
final revision = _authRevision;
final removal = machine?._agentRemovals[agent.id];
return (mode) async {
+ // A harness reviewed before it bound its first conversation is the
+ // same one once it has (`Agent.continuesSession`); the request below
+ // still names the reviewed identity, so the daemon decides whether a
+ // harness that bound since may close.
bool sameAgent(Agent? current) =>
- current != null &&
- current.createdAt == agent.createdAt &&
- current.sessionId == agent.sessionId;
+ current != null && current.continuesSession(agent);
final current = machine?.agents
.where((a) => a.id == agent.id)
.firstOrNull;
@@ -2639,7 +2641,9 @@ class AppNotifier extends ChangeNotifier {
(observed == null || !observed.isStopped)) {
_upsertAgent(
machine,
- agent.copyWith(
+ // The latest row seen, so a conversation bound since the review is
+ // kept on the stopped harness for reopening.
+ (observed ?? current!).copyWith(
status: 'stopped',
terminalAvailable: false,
clearClosePlan: true,
diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dart
index 659e2e2e2..6551ad98b 100644
--- a/desktop/test/session_close_test.dart
+++ b/desktop/test/session_close_test.dart
@@ -30,6 +30,14 @@ class _CloseConnection extends WsConn {
final targetedFailures = <(String, String), Map<String, dynamic>>{};
final requests = <String>[];
Completer<Map<String, dynamic>>? inspecting;
+
+ /// Runs as the daemon takes a close, before it answers: what the window
+ /// hears while the daemon works on it.
+ Future<void> Function(String mode)? whileClosing;
+
+ /// Whether a close is announced as `agent_deleted` before its answer. Off,
+ /// the window still lists the harness when the answer arrives.
+ bool announceClose = true;
@override
Future<Map<String, dynamic>> request(
String type, {
@@ -41,6 +49,7 @@ class _CloseConnection extends WsConn {
closes.add(Map.of(payload));
final mode = payload['mode'] as String;
final agentId = payload['agentId'] as String;
+ await whileClosing?.call(mode);
if (targetedFailures[(agentId, mode)] ?? failures[mode]
case final failure?) {
// Real WsConn throws refusals; returning a map would skip the production
@@ -58,10 +67,12 @@ class _CloseConnection extends WsConn {
}
if (mode == 'after_task') return {'deferred': true};
if (mode == 'cancel') return {'cancelled': true};
- await app.handleEventForTest('m', {
- 'type': 'agent_deleted',
- 'payload': {'agentId': payload['agentId']},
- });
+ if (announceClose) {
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': payload['agentId']},
+ });
+ }
return {'closed': true};
}
}
@@ -362,6 +373,196 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
+ test('a first conversation bound after the review is the same session', () {
+ final unbound = agent('a0', started: false);
+ final bound = agent('a0');
+ expect(bound.continuesSession(unbound), isTrue);
+ expect(unbound.continuesSession(unbound), isTrue);
+ expect(bound.continuesSession(bound), isTrue);
+ // Once a conversation was bound, another one or none is a change.
+ expect(agent('a0', sessionId: 'other').continuesSession(bound), isFalse);
+ expect(unbound.continuesSession(bound), isFalse);
+ // So is another registration under the same ID.
+ final relaunched = Agent(
+ id: 'a0',
+ name: 'Work a0',
+ engine: 'codex',
+ sessionId: 'conversation-a0',
+ createdAt: DateTime.utc(2026, 9, 30, 13),
+ );
+ expect(relaunched.continuesSession(unbound), isFalse);
+ });
+
+ /// What the daemon announces once Codex has bound its first conversation.
+ Future<void> bindConversation() => app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'a0',
+ 'name': 'Work a0',
+ 'engine': 'codex',
+ 'sessionId': 'conversation-a0',
+ 'createdAt': DateTime.utc(2026, 9, 30, 12).toIso8601String(),
+ 'closeSupported': true,
+ 'resumeMode': 'conversation',
+ 'terminal': {'available': true},
+ },
+ },
+ });
+
+ for (final closeTab in [false, true]) {
+ final view = closeTab ? 'tab' : 'pane';
+ // Codex 0.162.1 binds no conversation for its first seconds. A pane closed
+ // a second after it started was reviewed unbound; by Stop it had bound
+ // one, and Stop answered "The session changed. Check it before closing."
+ // with the harness still running (clean macOS VM, Desktop 1.2.65).
+ testWidgets(
+ 'Stop closes the $view of a harness that bound its conversation after the review',
+ (tester) async {
+ app.stateOf('m')!.agents = [agent('a0', started: false)];
+ connection.activities['a0'] = 'working';
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final tab = app.activeSwarm;
+ await mount(tester, app);
+ unawaited(
+ closeTab
+ ? app.requestCloseSwarm(tab.id)
+ : app.requestClosePane(pane.id),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('1 session is still working.'), findsOneWidget);
+ await bindConversation();
+ expect(app.stateOf('m')!.agents.single.sessionId, 'conversation-a0');
+ await tester.tap(find.widgetWithText(FilledButton, 'Stop'));
+ await tester.pumpAndSettle();
+ expect(modes(), ['inspect', 'now']);
+ // Both name the identity reviewed: no conversation. The daemon takes
+ // that from a harness still starting that has bound one since.
+ expect(connection.closes.map((r) => r['sessionId']), ['', '']);
+ expect(
+ find.text('The session changed. Check it before closing.'),
+ findsNothing,
+ );
+ expect(find.text('Stop not confirmed'), findsNothing);
+ expect(find.byType(Dialog), findsNothing);
+ expect(app.allPanes, isEmpty);
+ expect(app.swarms, closeTab ? isNot(contains(tab)) : anything);
+ final stopped = app.stateOf('m')!.agents.single;
+ expect(stopped.isStopped, isTrue);
+ expect(stopped.sessionId, 'conversation-a0');
+ expect(app.closedHistory, hasLength(1));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'a conversation bound while the daemon closes the $view is not a change',
+ (tester) async {
+ app.stateOf('m')!.agents = [agent('a0', started: false)];
+ connection
+ ..activities['a0'] = 'working'
+ ..announceClose = false
+ // The daemon waits for the conversation, closes with it, and the
+ // window hears the bind before the answer.
+ ..whileClosing = (mode) async {
+ if (mode == 'now') await bindConversation();
+ };
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final tab = app.activeSwarm;
+ await mount(tester, app);
+ unawaited(
+ closeTab
+ ? app.requestCloseSwarm(tab.id)
+ : app.requestClosePane(pane.id),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(FilledButton, 'Stop'));
+ await tester.pumpAndSettle();
+ expect(modes(), ['inspect', 'now']);
+ expect(find.text('Stop not confirmed'), findsNothing);
+ expect(find.byType(Dialog), findsNothing);
+ expect(app.allPanes, isEmpty);
+ final stopped = app.stateOf('m')!.agents.single;
+ expect(stopped.isStopped, isTrue);
+ expect(stopped.sessionId, 'conversation-a0');
+ expect(app.closedHistory, hasLength(1));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'a $view whose bound-since harness the daemon refuses can still be dismissed',
+ (tester) async {
+ // An older CLI, or a harness the daemon will not take unbound (a
+ // resume, one typed into a terminal): its refusal is the answer.
+ app.stateOf('m')!.agents = [agent('a0', started: false)];
+ connection
+ ..activities['a0'] = 'working'
+ ..targetedFailures[('a0', 'now')] = {'error': 'AGENT_CHANGED'};
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final tab = app.activeSwarm;
+ await mount(tester, app);
+ unawaited(
+ closeTab
+ ? app.requestCloseSwarm(tab.id)
+ : app.requestClosePane(pane.id),
+ );
+ await tester.pumpAndSettle();
+ await bindConversation();
+ await tester.tap(find.widgetWithText(FilledButton, 'Stop'));
+ await tester.pumpAndSettle();
+ expect(modes(), ['inspect', 'now']);
+ expect(find.text('Stop not confirmed'), findsOneWidget);
+ final sent = List.of(connection.closes);
+ await tester.tap(find.byKey(const Key('session-close-view')));
+ await tester.pumpAndSettle();
+ expect(connection.closes, sent);
+ expect(find.byType(Dialog), findsNothing);
+ expect(app.allPanes, isEmpty);
+ expect(app.swarms, closeTab ? isNot(contains(tab)) : anything);
+ expect(app.stateOf('m')!.agents.single.isStopped, isFalse);
+ expect(app.closedHistory, hasLength(1));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'another conversation after the review still stops nothing in the $view',
+ (tester) async {
+ connection.activities['a0'] = 'working';
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final tab = app.activeSwarm;
+ await mount(tester, app);
+ unawaited(
+ closeTab
+ ? app.requestCloseSwarm(tab.id)
+ : app.requestClosePane(pane.id),
+ );
+ await tester.pumpAndSettle();
+ app.stateOf('m')!.agents[0] = agent('a0', sessionId: 'replacement');
+ await tester.tap(find.widgetWithText(FilledButton, 'Stop'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('The session changed. Check it before closing.'),
+ findsOneWidget,
+ );
+ expect(modes(), ['inspect']);
+ await tester.tap(find.byKey(const Key('session-close-view')));
+ await tester.pumpAndSettle();
+ expect(app.panes, contains(pane));
+ expect(app.swarms, contains(tab));
+ expect(app.closedHistory, isEmpty);
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,
+ isFalse,
+ );
+ 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',