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.

Fix unused Companions and pane/tab close failures (#590)

Deec43b01863b43
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index 167dbae02..2675c6ef5 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -226,6 +226,7 @@ it.each([
it.each([
{ sessionId: 'existing-conversation' },
{ transcriptPath: '/tmp/existing-conversation.jsonl' },
+ { boundAt: 1 },
{ resumeOnly: true as const },
{ launch: { state: 'starting' as const } },
{ launch: { state: 'failed' as const, error: 'START_FAILED' } },
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index 1bd5330cf..637012980 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -20,7 +20,13 @@ export type AgentClosePlan = {
export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean }
export type AgentCloseResult = { closed?: true; deferred?: true; cancelled?: true; error?: string; detail?: string; activity?: CloseActivity }
-type CloseSession = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'launch' | 'resumeOnly'>
+type CloseSession = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'boundAt' | 'launch' | 'resumeOnly'>
+
+function unusedChat(session: CloseSession): boolean {
+ return (session.engine === 'claude' || session.engine === 'codex')
+ && !session.sessionId && !session.transcriptPath && session.boundAt == null && !session.resumeOnly
+ && (session.launch == null || session.launch.state === 'ready')
+}
/** An empty new chat has no turn state yet. Existing chats still require that state,
* and neither kind is idle without a recognized empty composer. */
@@ -37,10 +43,7 @@ export function inspectCloseActivity(session: CloseSession, screen: string | nul
const hold = teamWriteHold(engine, screen)
if (hold === 'team_waiting_draft') return 'draft'
if (hold === 'team_waiting_user') return 'needs_input'
- const unusedChat = (engine === 'claude' || engine === 'codex')
- && !session.sessionId && !session.transcriptPath && !session.resumeOnly
- && (session.launch == null || session.launch.state === 'ready')
- if (hold || (turnOpen === undefined && !unusedChat)) return 'unknown'
+ if (hold || (turnOpen === undefined && !unusedChat(session))) return 'unknown'
return 'idle'
}
@@ -140,6 +143,16 @@ export class CloseAgentService {
await this.deps.stop(s.agentId, {
current: () => !!current(),
checkpoint: (s, phase) => this.deps.checkpoint(s, phase),
+ confirmUnusedConversation: async captured => {
+ // A missing ID alone could be failed discovery of active work. Only
+ // an unused chat with a freshly observed empty composer can skip the
+ // shared-server conversation stop, after its screen is checkpointed.
+ const latest = current()
+ if (!latest || !unusedChat(captured) || !unusedChat(latest)) return false
+ const activity = await this.deps.activity(latest)
+ const after = current()
+ return activity === 'idle' && !!after && unusedChat(after)
+ },
beforeStop: async () => {
const latest = current()
if (!latest) throw new Error('The session changed while saving. Please try again.')
diff --git a/cli/src/lib/codexSessionLifecycle.spec.ts b/cli/src/lib/codexSessionLifecycle.spec.ts
index 9aad6c515..d20507b94 100644
--- a/cli/src/lib/codexSessionLifecycle.spec.ts
+++ b/cli/src/lib/codexSessionLifecycle.spec.ts
@@ -45,6 +45,26 @@ it('refuses an unreadable process table or an unbound conversation before contro
await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow('identify')
expect(deps.connect).not.toHaveBeenCalled()
})
+it('requires a verified process before accepting an unused conversation', async () => {
+ row.sessionId = ''
+ const confirmUnused = vi.fn(async () => true)
+ await expect(stopSharedCodexSession(row, () => true, deps, confirmUnused)).rejects.toThrow('identify')
+ expect(confirmUnused).not.toHaveBeenCalled()
+ expect(deps.connect).not.toHaveBeenCalled()
+})
+it('rechecks cancellation after confirming an unused conversation', async () => {
+ row.sessionId = ''
+ row.processIdentity = { pid: 99, executable: 'codex', startMarker: 'born' }
+ vi.mocked(deps.rows).mockResolvedValue([
+ ...(await deps.rows())!, { ...row.processIdentity, parentPid: 1, args: 'codex' },
+ ])
+ let current = true
+ await expect(stopSharedCodexSession(row, () => current, deps, async () => {
+ current = false
+ return true
+ })).rejects.toThrow('cancelled')
+ expect(deps.connect).not.toHaveBeenCalled()
+})
it('leaves a process-owned conversation and an unrelated shared server untouched', async () => {
loaded = false
await stopSharedCodexSession(row, () => true, deps)
@@ -120,3 +140,12 @@ it.each(['codex --remote ws://fixture.invalid resume conversation', 'codex resum
await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow('remote Codex server')
expect(deps.connect).not.toHaveBeenCalled()
})
+it('does not bypass a remote server for an unbound chat', async () => {
+ row.sessionId = ''
+ row.processIdentity = { pid: 99, executable: 'codex', startMarker: 'born' }
+ vi.mocked(deps.rows).mockResolvedValue([{ ...row.processIdentity, parentPid: 1, args: 'codex --remote=ws://fixture.invalid' }])
+ const confirmUnused = vi.fn(async () => true)
+ await expect(stopSharedCodexSession(row, () => true, deps, confirmUnused)).rejects.toThrow('remote Codex server')
+ expect(confirmUnused).not.toHaveBeenCalled()
+ expect(deps.connect).not.toHaveBeenCalled()
+})
diff --git a/cli/src/lib/codexSessionLifecycle.ts b/cli/src/lib/codexSessionLifecycle.ts
index bad587894..a0c571457 100644
--- a/cli/src/lib/codexSessionLifecycle.ts
+++ b/cli/src/lib/codexSessionLifecycle.ts
@@ -91,7 +91,8 @@ export interface CodexStopDeps {
/** Called AFTER a checkpoint and BEFORE signalling the terminal. There is no
* polling, model call, archive deletion or machine-wide daemon shutdown here. */
export async function stopSharedCodexSession(session: RegisteredSession, current: () => boolean,
- deps: CodexStopDeps = { daemonIdentity, rows: processRows, connect: connectCodexControl }): Promise<void> {
+ deps: CodexStopDeps = { daemonIdentity, rows: processRows, connect: connectCodexControl },
+ confirmUnusedConversation?: (session: RegisteredSession) => Promise<boolean>): Promise<void> {
if (session.engine !== 'codex') return
const home = session.codexHome || env.CODEX_HOME
const rows = await deps.rows()
@@ -113,9 +114,18 @@ export async function stopSharedCodexSession(session: RegisteredSession, current
if (!daemon) return // Older/process-owned Codex has no detached writer.
const normalize = (value: string) => value.trim().replace(/\s+/g, ' ')
if (!rows.some(row => row.pid === daemon.pid && normalize(row.startMarker) === normalize(daemon.processStartTime))) return
- if (!session.sessionId) throw new Error('Could not identify the conversation on the Codex server; the session is still open')
- const control = await deps.connect(home)
const guard = () => { if (!current()) throw new Error('The close request was cancelled or the session changed') }
+ if (!session.sessionId) {
+ // An unused TUI has no conversation to unload. Close supplies fresh proof
+ // of its empty composer after saving the screen; Pause and uncertain
+ // discovery still require an exact conversation identity.
+ if (owner && await confirmUnusedConversation?.(session)) {
+ guard()
+ return
+ }
+ throw new Error('Could not identify the conversation on the Codex server; the session is still open')
+ }
+ const control = await deps.connect(home)
try {
guard()
const read = await control.request('thread/read', { threadId: session.sessionId })
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index be0601c21..224645e48 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -37,6 +37,8 @@ export interface StopAgentOptions {
beforeStop?(session: RegisteredSession): Promise<void>
/** Retain native history before exit, then include anything the engine flushed while exiting. */
checkpoint?(session: RegisteredSession, phase: 'before' | 'after'): Promise<void>
+ /** Fresh proof that an unbound chat has never started and its composer is empty. */
+ confirmUnusedConversation?(session: RegisteredSession): Promise<boolean>
}
// Hooks rebuild registry objects. Compare stable values, never JavaScript object
@@ -85,7 +87,8 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
try {
markDeleted(sessionId)
if (s.sessionId) markDeleted(s.sessionId)
- await stopSharedCodexSession(s, () => sameTarget() && options.current?.() !== false)
+ await stopSharedCodexSession(s, () => sameTarget() && options.current?.() !== false,
+ undefined, options.confirmUnusedConversation)
// Keep the terminal alive while the engine handles SIGTERM and flushes
// its native store. Killing tmux in parallel can deliver SIGHUP first.
const termination = await (isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
diff --git a/cli/src/lib/unusedCodexClose.spec.ts b/cli/src/lib/unusedCodexClose.spec.ts
new file mode 100644
index 000000000..cfaa3013c
--- /dev/null
+++ b/cli/src/lib/unusedCodexClose.spec.ts
@@ -0,0 +1,96 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+import { registry, type RegisteredSession } from './registry.js'
+import { stoppedAgents } from './stoppedAgents.js'
+import { AgentRestartCoordinator } from './restartAgent.js'
+import { CloseAgentService, inspectCloseActivity } from './closeAgentService.js'
+import { createStopAgentService } from './stopAgentService.js'
+import { SessionCheckpointStore } from './sessionCheckpoint.js'
+import { processRows } from './tmux.js'
+import { terminateDeletedAgent } from './deleteAgentFallback.js'
+
+vi.mock('./tmux.js', async importOriginal => ({
+ ...await importOriginal<typeof import('./tmux.js')>(),
+ processRows: vi.fn(),
+}))
+vi.mock('./captureResumeIdentity.js', () => ({ captureResumeIdentity: vi.fn(async session => session) }))
+vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))
+
+// The old companion TUI shares a profile with a running server but has never
+// submitted a turn. Exercise the real Close -> Stop -> Codex lifecycle chain.
+const emptyComposer = '\u001b[1m›\u001b[0m \u001b[2mAsk Codex to do anything\u001b[0m\n\n GPT-6-Astra max · /tmp/companions\n ? for shortcuts'
+let row: RegisteredSession
+let service: CloseAgentService
+let screen: string | null
+let checkpointDirectory: string
+const killPane = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ row = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%500' }], cwd: '/tmp/companions' })!
+ Object.assign(row, {
+ launch: { state: 'ready' },
+ dsh: 'autonomous/pair',
+ codexHome: join(env.ADAPTER_DATA_DIR, 'unused-codex', row.agentId),
+ processIdentity: { pid: 99, executable: 'node', startMarker: 'old companion' },
+ })
+ mkdirSync(join(row.codexHome!, 'app-server-daemon'), { recursive: true })
+ writeFileSync(join(row.codexHome!, 'app-server-daemon', 'daemon.pid'), JSON.stringify({ pid: 78, processStartTime: 'shared server' }))
+ vi.mocked(processRows).mockResolvedValue([
+ { ...row.processIdentity!, parentPid: 1, args: 'node /bin/codex -c mcp_servers.harnessd.command="harness"' },
+ { pid: 78, parentPid: 1, executable: 'codex', startMarker: 'shared server', args: 'codex app-server' },
+ ])
+ screen = emptyComposer
+ vi.mocked(terminateDeletedAgent).mockResolvedValue('terminated')
+ const stop = createStopAgentService({
+ registry, stoppedAgents, restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(),
+ tmuxBackend: { kill: killPane },
+ agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },
+ forgetSession: id => registry.removeAgent(id), markDeleted: vi.fn(), clearDeleted: vi.fn(),
+ })
+ checkpointDirectory = join(env.ADAPTER_DATA_DIR, 'unused-checkpoints', row.agentId)
+ const checkpoints = new SessionCheckpointStore(checkpointDirectory)
+ service = new CloseAgentService({
+ registry, stop, changed: vi.fn(),
+ activity: async session => inspectCloseActivity(session, screen, undefined, false),
+ checkpoint: (session, phase) => checkpoints.save(session, { screen: phase === 'before' ? screen : null }),
+ })
+})
+afterEach(() => {
+ service.dispose()
+ vi.restoreAllMocks()
+ for (const entry of registry.list()) registry.removeAgent(entry.agentId)
+})
+
+it.each(['idle', 'now'] as const)('closes an unused companion with a shared Codex server after saving its terminal (%s)', async mode => {
+ const request = { agentId: row.agentId, sessionId: '', createdAt: new Date(row.registeredAt).toISOString() }
+ expect(await service.request({ ...request, mode: 'inspect' })).toEqual({ activity: 'idle' })
+ expect(await service.request({ ...request, mode })).toEqual({ closed: true })
+ expect(terminateDeletedAgent).toHaveBeenCalledOnce()
+ expect(vi.mocked(terminateDeletedAgent).mock.calls[0][0].processIdentity?.pid).toBe(99)
+ expect(killPane).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%500' })
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+ const manifest = JSON.parse(readFileSync(join(checkpointDirectory, readdirSync(checkpointDirectory).find(file => /^[a-f0-9]{64}\.json$/.test(file))!), 'utf8'))
+ expect(JSON.parse(readFileSync(join(checkpointDirectory, manifest.file), 'utf8')).screen).toBe(emptyComposer)
+})
+
+it.each(['working', 'draft', 'unreadable', 'bound', 'resuming'] as const)('does not bypass an unknown shared conversation when %s', async state => {
+ // The final check happens after saving, even when Close was explicitly
+ // confirmed. No conversation ID must not mean arbitrary work can be stopped.
+ const rows = vi.mocked(processRows).getMockImplementation()!
+ vi.mocked(processRows).mockImplementation(async () => {
+ if (state === 'working') screen = '• Working (4s · esc to interrupt)\n›\n 100% context left'
+ if (state === 'draft') screen = '› Keep this draft\n 100% context left'
+ if (state === 'unreadable') screen = null
+ if (state === 'bound') row.boundAt = 1
+ if (state === 'resuming') row.resumeOnly = true
+ return rows()
+ })
+ expect(await service.request({ agentId: row.agentId, sessionId: '', createdAt: new Date(row.registeredAt).toISOString(), mode: 'now' }))
+ .toMatchObject({ error: 'CLOSE_FAILED' })
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ expect(killPane).not.toHaveBeenCalled()
+ expect(registry.byAgent(row.agentId)).toBe(row)
+})
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 60fde96f2..6ea518a28 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2213,6 +2213,14 @@ class AppNotifier extends ChangeNotifier {
'mode': mode,
},
);
+ } on WsRequestFailure catch (failure) {
+ // A refusal is an answer, not a lost connection. Keep its activity so
+ // SESSION_NOT_IDLE can be reviewed, and its save/stop detail for the user.
+ result = {
+ ...failure.payload,
+ 'error': failure.code,
+ if (failure.detail != null) 'detail': failure.detail,
+ };
} catch (_) {
// A lost reply never causes a second Stop. Authoritative saved inventory
// can confirm it; otherwise keep the pane and report uncertainty.
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index a3429afbc..b25152525 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -48,6 +48,7 @@ class WsRequestFailure implements Exception {
required this.responseType,
required this.code,
this.detail,
+ this.payload = const {},
});
/// The frame that carried the refusal — `agent_create_result`, say.
@@ -60,6 +61,10 @@ class WsRequestFailure implements Exception {
/// SPAWN_FAILED. Already reads as a sentence; prefer it to anything rewritten from [code].
final String? detail;
+ /// Additional reply fields needed to handle a refusal, such as the activity
+ /// that made an idle Close unsafe. These must survive the error boundary.
+ final Map<String, dynamic> payload;
+
@override
String toString() => detail == null || detail!.isEmpty
? '$responseType: $code'
@@ -552,6 +557,7 @@ class WsConn {
responseType: message['type'] as String? ?? 'unknown_result',
code: '${payload['error']}',
detail: detail is String && detail.isNotEmpty ? detail : null,
+ payload: Map.unmodifiable(payload),
),
);
} else {
diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dart
index 59133ffe4..a84d34bf8 100644
--- a/desktop/test/session_close_test.dart
+++ b/desktop/test/session_close_test.dart
@@ -25,22 +25,33 @@ class _CloseConnection extends WsConn {
late AppNotifier app;
final closes = <Map<String, dynamic>>[];
final activities = <String, String>{};
+ final failures = <String, Map<String, dynamic>>{};
+ final requests = <String>[];
Completer<Map<String, dynamic>>? inspecting;
- Map<String, dynamic>? failure;
@override
Future<Map<String, dynamic>> request(
String type, {
Map<String, dynamic> payload = const {},
Duration timeout = const Duration(seconds: 20),
}) async {
+ requests.add(type);
if (type != 'agent_close') return {};
closes.add(Map.of(payload));
final mode = payload['mode'];
+ if (failures[mode] case final failure?) {
+ // Real WsConn throws refusals; returning a map would skip the production
+ // error path and hide the bug that called every refusal a lost reply.
+ throw WsRequestFailure(
+ responseType: 'agent_close_result',
+ code: failure['error'] as String,
+ detail: failure['detail'] as String?,
+ payload: failure,
+ );
+ }
if (mode == 'inspect') {
return inspecting?.future ??
Future.value({'activity': activities[payload['agentId']] ?? 'idle'});
}
- if (failure != null) return failure!;
if (mode == 'after_task') return {'deferred': true};
if (mode == 'cancel') return {'cancelled': true};
await app.handleEventForTest('m', {
@@ -218,7 +229,7 @@ void main() {
testWidgets('a failed disk checkpoint leaves the pane and explains why', (
tester,
) async {
- connection.failure = {
+ connection.failures['idle'] = {
'error': 'HISTORY_NOT_SAVED',
'detail': 'Not enough free disk space.',
};
@@ -232,6 +243,59 @@ void main() {
expect(app.panes, [pane]);
expect(app.closedHistory, isEmpty);
expect(modes(), ['inspect', 'idle']);
+ expect(connection.requests, isNot(contains('agents_list')));
+ 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',
+ (tester) async {
+ connection.failures['idle'] = {
+ 'error': 'SESSION_NOT_IDLE',
+ 'activity': 'working',
+ };
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ unawaited(
+ closeTab
+ ? app.requestCloseSwarm(app.activeSwarmId)
+ : app.requestClosePane(pane.id),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Still working. Close anyway?'), findsOneWidget);
+ expect(app.panes, [pane]);
+ expect(modes(), ['inspect', 'idle']);
+ await tester.tap(find.byKey(const Key('session-close-now')));
+ await tester.pumpAndSettle();
+ expect(modes(), ['inspect', 'idle', 'now']);
+ expect(app.allPanes, isEmpty);
+ expect(app.closedHistory, hasLength(1));
+ expect(connection.requests, isNot(contains('agents_list')));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('Cancel after activity changes leaves the session running', (
+ tester,
+ ) async {
+ connection.failures['idle'] = {
+ 'error': 'SESSION_NOT_IDLE',
+ 'activity': 'draft',
+ };
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ unawaited(app.requestClosePane(pane.id));
+ await tester.pumpAndSettle();
+ expect(find.text('Unsent text. Close anyway?'), findsOneWidget);
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(modes(), ['inspect', 'idle']);
+ expect(app.panes, [pane]);
+ expect(app.closedHistory, isEmpty);
+ expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
await tester.pumpWidget(const SizedBox());
});
diff --git a/desktop/test/ws_conn_test.dart b/desktop/test/ws_conn_test.dart
index bca4179bd..da8635dff 100644
--- a/desktop/test/ws_conn_test.dart
+++ b/desktop/test/ws_conn_test.dart
@@ -2,7 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
-import 'package:harness/core/models.dart' show ConnectionStatus;
+import 'package:harness/core/models.dart' show Agent, ConnectionStatus;
import 'package:harness/ws/ws_conn.dart';
import 'package:harness/ws/ws_pool.dart';
import 'package:harness/logging/app_log.dart';
@@ -11,6 +11,8 @@ import 'package:harness/logging/log_stream.dart';
import 'package:harness/logging/log_stream_sinks.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'swarm_state_test.dart' show createApp;
+
class FakeHub {
final HttpServer server;
final bool rejectOldToken;
@@ -20,6 +22,7 @@ class FakeHub {
final List<String?> environments = [];
final Map<String, int> machineSelected = {};
final List<WebSocket> clients = [];
+ Map<String, dynamic> closeResponse = {'activity': 'idle'};
FakeHub._(this.server, this.rejectOldToken, this.closeCodeOnSelect);
int get port => server.port;
@@ -79,6 +82,16 @@ class FakeHub {
},
}),
);
+ } else if (frame['type'] == 'agent_close') {
+ ws.add(
+ jsonEncode({
+ 'type': 'agent_close_result',
+ 'payload': {
+ 'requestId': (frame['payload'] as Map)['requestId'],
+ ...hub.closeResponse,
+ },
+ }),
+ );
} else if (frame['type'] == 'agents_list') {
ws.add(
jsonEncode({
@@ -272,6 +285,47 @@ void main() {
},
);
+ for (final failure in [
+ {'error': 'SESSION_NOT_IDLE', 'activity': 'working'},
+ {'error': 'HISTORY_NOT_SAVED', 'detail': 'Not enough free disk space.'},
+ ]) {
+ test('close preserves ${failure['error']} across the real WebSocket', () async {
+ hub = await FakeHub.start();
+ hub.closeResponse = failure;
+ conn = WsConn(
+ wsBaseUrl: 'ws://127.0.0.1:${hub.port}',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: Uri.parse('ws://127.0.0.1:${hub.port}/api/local-ws'),
+ );
+ final app = createApp(connected: true, connectionForTest: (_) => conn!);
+ addTearDown(app.dispose);
+ final agent = Agent(
+ id: 'a0',
+ engine: 'codex',
+ name: 'Work',
+ sessionId: 'conversation-a0',
+ createdAt: DateTime.utc(2026, 10, 1),
+ closeSupported: true,
+ terminalAvailable: true,
+ );
+ app.stateOf('m')!.agents = [agent];
+ await conn!.connect();
+ final result = await app.prepareSessionClose('m', agent)('idle');
+ for (final entry in failure.entries) {
+ expect(result[entry.key], entry.value);
+ }
+ expect(app.stateOf('m')!.agents.single.isStopped, isFalse);
+ expect(hub.frames.where((f) => f['type'] == 'agent_close'), hasLength(1));
+ expect(hub.frames.where((f) => f['type'] == 'agents_list'), isEmpty);
+ });
+ }
+
test('forceReconnect() sends forceReconnect:true on the next machine_select, only for local transport', () async {
hub = await FakeHub.start();
conn = WsConn(