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
Keep a pane as its shell after the engine exits (#600); Delete Harness on desktop (#1312)
Bubu-Dudu-52hz96a9b7bdeb94
diff --git a/cli/e2e/ends.e2e.ts b/cli/e2e/ends.e2e.tsindex 3a65109c5..44b887971 100644--- a/cli/e2e/ends.e2e.ts+++ b/cli/e2e/ends.e2e.ts@@ -298,10 +298,10 @@ describe('how an agent\'s life ends', () => {client.close()})- // A failed start (Claude Code that cannot reach Anthropic) keeps its pane on the shell it leaves,- // where its last screen says why: agent_deleted names that shell as `successor`. An agent that- // exits after doing work still ends as before (#262).- it('an agent that exits before any conversation hands its pane to the shell; one after a turn does not', async () => {+ // An engine that exits keeps its pane on the shell it leaves: agent_deleted names that shell as+ // `successor`. A failed start (Claude Code that cannot reach Anthropic) keeps its last screen, which+ // says why; one after work keeps the terminal the pane says it is now (#600).+ it('an agent that exits hands its pane to the shell, before any conversation and after a turn', async () => {const d = await fresh()const client = await LocalClient.connect(d)const early = await create(d, client, 'claude', 'exit-at-start')@@ -317,7 +317,9 @@ describe('how an agent\'s life ends', () => {await turn(client, worked.id, 'a real first task')const ended = client.next((frame) => frame.type === 'agent_deleted' && frame.payload?.agentId === worked.id, 45_000, 'agent_deleted (after work)')client.send('message', { agentId: worked.id, content: '!exit' })- expect((await ended).payload?.successor).toBeUndefined()+ const after = (await ended).payload?.successor as string | undefined+ expect(after).toBeTruthy()+ expect((await until('the shell after work', async () => (await row(client, after!)) ?? null, 30_000, 500)).engine).toBe('terminal')})it('a close for an agent that is not the one asked about changes nothing', async () => {diff --git a/cli/e2e/paneLifecycle.e2e.ts b/cli/e2e/paneLifecycle.e2e.tsnew file mode 100644index 000000000..da6b691d4--- /dev/null+++ b/cli/e2e/paneLifecycle.e2e.ts@@ -0,0 +1,73 @@+/**+ * A pane whose engine was stopped by hand stays the person's (#600). Ctrl-C to stop Codex, after it has+ * worked, left the pane a shell that said so ("This pane is a shell now — run codex again, or stop the+ * pane"), and 10–15 s later the window closed it: the daemon told it the agent had ended and named no+ * shell to move to. Now the window is told to move there, the shell is still there long after, Ctrl-D in+ * it ends it the usual way, and a close of the harness that ended is answered at once.+ */+import { mkdirSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++type Engine = 'claude' | 'codex'+type Row = Record<string, any>+const engines: Engine[] = ['claude', 'codex']+const rows = async (client: LocalClient): Promise<Row[]> =>+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)+const deleted = (client: LocalClient, agentId: string, what: string) =>+ client.next((frame) => frame.type === 'agent_deleted' && frame.payload?.agentId === agentId, 45_000, what)++let daemon: IsolatedDaemon | null = null+afterEach(async () => { await daemon?.stop(); daemon = null })++describe('a pane whose engine was stopped by hand (#600)', () => {+ it.each(engines)('%s: the pane stays a shell after the engine exits, and Ctrl-D in it ends it cleanly', async (engine) => {+ const d = await IsolatedDaemon.create()+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ const client = await LocalClient.connect(d)+ const cwd = join(d.projectsDir, `stopped-by-hand-${engine}`)+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 120_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ const agent = await until('the conversation to bind', async () => {+ const found = await row(client, created.agent.id)+ return found?.sessionId && found.status === 'active' ? found : null+ }, 60_000, 500)+ const ended = client.next((frame) => frame.type === 'turn_ended' && frame.agentId === agent.id, 45_000, 'turn_ended')+ client.send('message', { agentId: agent.id, content: 'some real work first' })+ await ended+ const pane = String(agent.tmuxPane)++ // Typed into the pane, as a person quits the engine.+ const gone = deleted(client, agent.id, 'agent_deleted (the engine)')+ await d.tmux.run('send-keys', '-t', pane, '-l', '!exit')+ await d.tmux.run('send-keys', '-t', pane, 'Enter')+ const successor = (await gone).payload?.successor as string | undefined+ expect(successor, 'the window is told which shell keeps the pane').toBeTruthy()+ const shell = await until('the shell row', async () => (await row(client, successor!)) ?? null, 30_000, 500)+ expect(shell.engine).toBe('terminal')+ expect(shell.tmuxPane).toBe(pane)+ expect(await d.capture(pane)).toContain('This pane is a shell now')++ // Well past the 10–15 s after which the pane used to go.+ await new Promise((resolve) => setTimeout(resolve, 20_000))+ expect((await row(client, successor!))?.status).toBe('active')+ expect((await d.tmux.run('display-message', '-p', '-t', pane, '#{pane_dead}')).trim()).toBe('0')+ // The harness that ended is closed already: a close of it is answered at once, never left unconfirmed.+ const closed = await client.request('agent_close', { agentId: agent.id, sessionId: agent.sessionId, createdAt: agent.createdAt, mode: 'now' }, 15_000)+ expect(closed).toMatchObject({ closed: true })++ // Ctrl-D ends the shell, and with it the pane and its row.+ const shellGone = deleted(client, successor!, 'agent_deleted (the shell)')+ await d.tmux.run('send-keys', '-t', pane, 'C-d')+ await shellGone+ await until('the shell to stop counting as active', async () => (await row(client, successor!))?.status !== 'active' || null, 30_000, 500)+ await until('the pane to go', async () => !(await d.tmux.run('list-panes', '-a', '-F', '#{pane_id}').catch(() => '')).split('\n').includes(pane) || null, 15_000, 250)+ client.close()+ }, 240_000)+})diff --git a/cli/src/lib/retainExitedSession.spec.ts b/cli/src/lib/retainExitedSession.spec.tsindex 15ede437b..4dd924d6d 100644--- a/cli/src/lib/retainExitedSession.spec.ts+++ b/cli/src/lib/retainExitedSession.spec.ts@@ -1,5 +1,5 @@import { describe, it, expect, vi } from 'vitest'-import { createRetainExitedSession, EARLY_EXIT_MS, type RetainExitedSessionDeps } from './retainExitedSession.js'+import { createRetainExitedSession, type RetainExitedSessionDeps } from './retainExitedSession.js'import type { RegisteredSession } from './registry.js'const row = (over: Partial<RegisteredSession> = {}): RegisteredSession => ({@@ -40,12 +40,12 @@ function harness(over: Partial<RetainExitedSessionDeps> = {}) {}describe('retainExitedSession', () => {- it('ends the identity that was running the engine so its views close, and keeps the surviving shell', () => {+ it('ends the identity that was running the engine so its views move to the surviving shell', () => {const h = harness()const entry = row()h.retain(entry, true)- expect(h.frames).toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true } }])+ expect(h.frames).toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true, successor: 'agent-shell' } }])expect(h.calls.indexOf('release:agent-a:true')).toBeLessThan(h.calls.indexOf('send:agent_deleted'))// The archive exists BEFORE the client is told to go looking for it, and the ending reaches the// client before the frame that is behind an await.@@ -57,31 +57,17 @@ describe('retainExitedSession', () => {expect(h.calls).toContain('announce:agent-shell')})- // Only a failed start hands its tiles to the shell: there the engine's last screen is the only- // place that says why it stopped. A later exit keeps closing its views (#262).- it('an engine that exits soon after it appeared names the shell that keeps its pane', () => {- const quickExit = harness({ now: () => 1_000 + 30_000, hadConversation: () => true })- quickExit.retain(row({ registeredAt: 1_000 }), true)- expect(quickExit.frames, 'a quick /exit after real work closes as before').toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true } }])- const h = harness({ now: () => 1_000 + 30_000, hadConversation: () => false })- h.retain(row({ registeredAt: 1_000 }), true)- expect(h.frames).toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true, successor: 'agent-shell' } }])- const late = harness({ now: () => 1_000 + EARLY_EXIT_MS, hadConversation: () => false })- late.retain(row({ registeredAt: 1_000 }), true)- expect(late.frames).toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true } }])- const noTranscript = harness({ now: () => 1_000 + 30_000 })- noTranscript.retain(row({ registeredAt: 1_000, engine: 'opencode', transcriptPath: null }), true)- expect(noTranscript.frames, 'an engine that keeps no transcript: an ending').toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true } }])- for (const engine of ['claude', 'codex'] as const) {- const neverWrote = harness({ now: () => 1_000 + 30_000 })- neverWrote.retain(row({ registeredAt: 1_000, engine, transcriptPath: null }), true)- expect(neverWrote.frames[0]!.payload.successor, `${engine} that failed before writing a transcript`).toBe('agent-shell')+ // Every exit that leaves its pane a shell hands its tiles to that shell, a failed start or one after+ // work: the pane says it is a shell now, and Ctrl-C to stop Codex must not take it away (#600).+ it('an engine whose pane outlived it names the shell that keeps the pane', () => {+ for (const exited of [row(), row({ transcriptPath: null }), row({ engine: 'opencode', transcriptPath: null }),+ row({ registeredAt: 1_000, touchedAt: 1_000 + 24 * 3_600_000 })]) {+ const h = harness()+ h.retain(exited, true)+ expect(h.frames, exited.engine).toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true, successor: 'agent-shell' } }])}- const unwritten = harness({ now: () => 1_000 + 30_000 })- unwritten.retain(row({ registeredAt: 1_000, transcriptPath: '/nonexistent/never-written.jsonl' }), true)- expect(unwritten.frames[0]!.payload.successor).toBe('agent-shell')- const dead = harness({ now: () => 1_000, hadConversation: () => false })- dead.retain(row({ registeredAt: 1_000 }), false)+ const dead = harness()+ dead.retain(row(), false)expect(dead.frames).toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true } }])})diff --git a/cli/src/lib/retainExitedSession.ts b/cli/src/lib/retainExitedSession.tsindex 3c5cfa1b0..045a18303 100644--- a/cli/src/lib/retainExitedSession.ts+++ b/cli/src/lib/retainExitedSession.ts@@ -11,7 +11,6 @@* steps is the part worth testing — the archive must exist before a client is told to look for it,* and the ending must reach the client before the frame that is behind a filesystem await.*/-import { statSync } from 'node:fs'import type { RegisteredSession } from './registry.js'export interface RetainExitedSessionDeps {@@ -34,28 +33,8 @@ export interface RetainExitedSessionDeps {detachDsh(agentId: string): voidsyncRecapPool(): voidwarn(message: string, error: unknown): void- /** Injected for tests; Date.now otherwise. */- now?: () => number- /** Whether the engine wrote any conversation; the transcript on disk otherwise. */- hadConversation?: (entry: RegisteredSession) => boolean}-/** Engines that write a transcript file once a conversation starts, so no file means none started. */-const KEEPS_TRANSCRIPT = new Set(['claude', 'codex'])--function wroteTranscript(entry: RegisteredSession): boolean {- // An engine that keeps no transcript file (OpenCode, the default) cannot show it wrote nothing,- // so its exit is an ending as before, not a failed start. Claude Code and Codex do keep one, and- // one that failed before writing it has no path at all: Claude Code that could not reach Anthropic- // right after Harness installed it closed its pane and tab with no message (fresh macOS VM,- // 2026-10-08, after #1047's handover, which this case slipped past).- if (!entry.transcriptPath) return !KEEPS_TRANSCRIPT.has(entry.engine)- try { return statSync(entry.transcriptPath).size > 0 } catch { return false }-}--/** How soon after it appeared an engine's exit counts as a failed start rather than an ending. */-export const EARLY_EXIT_MS = 2 * 60_000-export function createRetainExitedSession(deps: RetainExitedSessionDeps) {/** Retain the conversation's identity; a surviving shell gets its own live identity. */return (entry: RegisteredSession, paneAlive: boolean): void => {@@ -65,7 +44,8 @@ export function createRetainExitedSession(deps: RetainExitedSessionDeps) {deps.forgetInput(entry.agentId)deps.forgetRelaunch?.(entry.sessionId)deps.detachDsh(entry.agentId)- // CLOSE THE VIEWS OF THE AGENT THAT JUST ENDED, the way a stop does.+ // END THE VIEWS OF THE AGENT THAT JUST ENDED: moved to the shell that keeps its pane, or closed,+ // the way a stop closes them, when there is none.//// This identity has no runtime left: a surviving shell continues under a new one, and the// conversation is now an archive to be opened. The `agent_synced` below says so, but a client@@ -76,19 +56,17 @@ export function createRetainExitedSession(deps: RetainExitedSessionDeps) {// client re-reads its inventory and finds it among the saved harnesses. Sent BEFORE the archive// frame, which is behind an await, so the view closes at once rather than a filesystem turn later.//- // An engine that exits soon after it was started names the shell that keeps its pane as- // `successor`, so a window moves its tiles there instead of closing them: the engine's last- // screen is the only place that says why it stopped. A first Claude Code harness that could not- // reach Anthropic closed its only pane and left a new user on an empty box with no message (fresh- // macOS VM, 2026-10-08). Any later exit (`/exit`, Ctrl-C after work) still closes its views as- // above. The shell is released first (synchronous), so the frame still goes out before anything- // awaited.+ // An engine whose pane outlived it names the shell that keeps that pane as `successor`, so a+ // window moves its tiles there instead of closing them. The pane says so ("This pane is a shell+ // now — run codex again, or stop the pane"), and the person decides: run the engine again, run+ // anything else, or close it. Closing the views of a later exit took the pane away 10–15 s+ // after a Ctrl-C that only meant to stop Codex, the shell still running out of sight (#600).+ // A failed start keeps its last screen, the only place that says why it stopped, the same way+ // (fresh macOS VM, 2026-10-08). A pane that died with its engine has no successor, and its+ // views close as above. The shell is released first (synchronous), so the frame still goes out+ // before anything awaited.const terminal = paneAlive ? deps.registry.releaseEngine(entry.agentId, true) : null- // A failed start: soon after it appeared, and before it wrote any conversation. Time alone- // also caught a person who ran one quick task and typed /exit (review of #1047).- const early = (deps.now?.() ?? Date.now()) - entry.registeredAt < EARLY_EXIT_MS- && !(deps.hadConversation ?? wroteTranscript)(entry)- deps.send({ type: 'agent_deleted', payload: { agentId: entry.agentId, retained: true, ...(terminal && early ? { successor: terminal.agentId } : {}) } })+ deps.send({ type: 'agent_deleted', payload: { agentId: entry.agentId, retained: true, ...(terminal ? { successor: terminal.agentId } : {}) } })if (!paneAlive) deps.registry.removeAgent(entry.agentId)deps.syncRecapPool()void deps.publishStoppedAgent(saved).catch(error => deps.warn('[resume] could not announce saved harness', error))diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 2626eea2d..ba9b05257 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -108,6 +108,7 @@ import '../state/toolbar_notices.dart';import '../widgets/machine_actions.dart';import '../widgets/rename_agent_dialog.dart';import '../widgets/delete_agent_dialog.dart';+import '../widgets/delete_harness_dialog.dart';import '../widgets/fork_agent_dialog.dart';import '../widgets/restart_agent_action.dart';import '../measurement/task_feedback.dart';@@ -2802,6 +2803,31 @@ class _SwarmScreenState extends State<SwarmScreen> {);});+ /// Delete Harness: the focused pane's harness, or the row selected in Open+ /// Harness, running or stopped. Stop keeps a conversation to reopen; this+ /// is how one leaves the list.+ Future<void> _deleteHarness(String machineId, String agentId) => _dialog(+ () async {+ final machine = app.stateOf(machineId);+ final agent = machine?.agents+ .where((agent) => agent.id == agentId)+ .firstOrNull;+ if (agent == null || machine!.machine.isShared) return;+ if (isTerminalEngine(agent.engine)) {+ _showPaneActionHint('A terminal keeps no conversation. Stop it instead.');+ return;+ }+ await confirmDeleteHarness(+ context,+ app,+ machineId,+ agentId,+ agent.displayName,+ keymap: _keymap,+ );+ },+ );+/// ⌘⇧E — the focused pane's harness starts again where it is. Same routing/// as [_cloneAgent]: gated everywhere but the native menu's fallback path,/// which answers rather than doing nothing.@@ -6216,6 +6242,10 @@ class _SwarmScreenState extends State<SwarmScreen> {onCommands: _showSearchCommands,previewControls: _previewControls,onRefocus: _focusSearch,+ onDelete: (row) async {+ await _deleteHarness(row.machineId!, row.agentId!);+ _focusSearch();+ },child: FocusScope(node: _searchDialogScope, child: scoped),);return Stack(@@ -6822,6 +6852,12 @@ class _SwarmScreenState extends State<SwarmScreen> {if (focused != null) await _showSessionWork(focused);},'agent.stop': () => _editAgent(stop: true),+ 'agent.delete': () {+ final pane = app.focusedPane;+ if (pane?.agentId case final agentId?) {+ unawaited(_deleteHarness(pane!.machineId, agentId));+ }+ },'agent.fork': _forkAgent,'pane.toggle_viewer': _toggleFocusedViewer,'pane.toggle_composer': () {@@ -6886,6 +6922,18 @@ class _SwarmScreenState extends State<SwarmScreen> {if (id == 'app.onboarding_review') {return app.viewer == null;}+ if (id == 'agent.delete') {+ final pane = app.focusedPane;+ final machine = pane == null ? null : app.stateOf(pane.machineId);+ final agent = machine?.agents+ .where((agent) => agent.id == pane!.agentId)+ .firstOrNull;+ // A terminal has no conversation to delete: Stop Terminal ends it.+ return machine != null &&+ !machine.machine.isShared &&+ agent != null &&+ !isTerminalEngine(agent.engine);+ }if (id == 'agent.rename' ||id == 'agent.stop' ||id == 'agent.fork' ||diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex 236250ebb..5643494c7 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -371,6 +371,13 @@ final harnessCommands = <HarnessCommand>[],),const HarnessCommand('agent.stop', 'Stop Harness', ShortcutGroup.actions),+ // Stop keeps the conversation to reopen; Delete removes it for good.+ const HarnessCommand(+ 'agent.delete',+ 'Delete Harness',+ ShortcutGroup.actions,+ keywords: ['remove', 'purge', 'forget', 'conversation'],+ ),const HarnessCommand('app.product_feedback', 'Rate task outcome', ShortcutGroup.actions,keywords: ['feedback', 'completed', 'useful', 'problem']),const HarnessCommand('agent.fork', 'Fork Harness', ShortcutGroup.actions),@@ -778,6 +785,15 @@ final harnessCommands = <HarnessCommand>[extraKeys: ['cmd+period'],context: KeymapContext.picker,),+ // Open Harness: the selected harness, running or stopped, deleted for good.+ // ⌘⌫ is the search field's own delete-to-start, so not that.+ const HarnessCommand(+ 'picker.delete',+ 'Delete the selected harness',+ ShortcutGroup.actions,+ extraKeys: ['cmd+shift+backspace'],+ context: KeymapContext.picker,+ ),// Launch and Project use arrows/Enter. Keep stable command identities for// explicit user bindings without reserving plain letters in these prompts.for (final (name, key, label) in [diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 7a7c7cf38..a1f6f90e8 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -13067,6 +13067,63 @@ class AppNotifier extends ChangeNotifier {}}+ /// Delete Harness: unlike Stop, which keeps the conversation to reopen, this+ /// stops a running harness and deletes its saved conversation for good, so it+ /// leaves Open Harness too. The daemon's reviewed deletion (`agent_purge`):+ /// reviewed first, then deleted under that review. Project files and+ /// worktrees are kept. Null on success, or a message for the prompt.+ Future<String?> purgeAgent(String machineId, String agentId) async {+ final machine = machineStates[machineId];+ final agent = machine?.agents+ .where((agent) => agent.id == agentId)+ .firstOrNull;+ final createdAt = agent?.createdAt;+ if (machine == null || agent == null || createdAt == null) {+ return 'This harness is no longer listed. Refresh and try again.';+ }+ final sessionId = agent.sessionId;+ final target = {+ 'agentId': agentId,+ 'sessionId': sessionId == null || sessionId.isEmpty ? null : sessionId,+ 'createdAt': createdAt.millisecondsSinceEpoch,+ };+ String refused(Object? code, Object? detail) =>+ 'Delete failed: ${detail is String && detail.isNotEmpty ? detail : code}';+ try {+ final review = await _conn(machineId).request(+ 'agent_purge',+ payload: {...target, 'mode': 'inspect'},+ timeout: const Duration(seconds: 30),+ );+ if (review['error'] != null) {+ return refused(review['error'], review['detail']);+ }+ final reviewId = review['reviewId'];+ if (reviewId is! String) return 'Could not review this harness for deletion.';+ final result = await _conn(machineId).request(+ 'agent_purge',+ payload: {...target, 'mode': 'delete', 'reviewId': reviewId},+ timeout: const Duration(seconds: 60),+ );+ if (result['error'] != null) {+ return refused(result['error'], result['detail']);+ }+ if (result['deleted'] != true) {+ return 'Could not confirm the deletion. Refresh harnesses to check.';+ }+ } on WsRequestFailure catch (failure) {+ return refused(failure.code, failure.detail);+ } on WsRequestTimeout {+ return 'Could not confirm the deletion. Refresh harnesses to check.';+ } catch (_) {+ return 'Could not delete the harness. Try again.';+ }+ await _removeAgent(machine, agentId);+ unawaited(_loadMachineData(machine, force: true));+ notifyListeners();+ return null;+ }+bool _restartCurrent(AgentRestartAttempt attempt, {bool beforeSend = false}) {final machine = attempt._machine;final agent = attempt.agent;diff --git a/desktop/lib/widgets/delete_harness_dialog.dart b/desktop/lib/widgets/delete_harness_dialog.dartnew file mode 100644index 000000000..347a455a2--- /dev/null+++ b/desktop/lib/widgets/delete_harness_dialog.dart@@ -0,0 +1,194 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shortcuts/app_keymap.dart';+import '../state/app_state.dart';+import '../shared/theme/app_theme.dart' as grid;+import 'desktop_chrome.dart';+import 'desktop_prompt_surface.dart';+import 'box_chrome.dart' show BoxAnnouncer;+import 'terminal_prompt.dart';++/// Delete Harness: a harness and its saved conversation, gone for good+/// ([AppNotifier.purgeAgent]). Stop keeps the conversation to reopen; this is+/// how a harness leaves Open Harness. Running or stopped alike.+Future<void> confirmDeleteHarness(+ BuildContext context,+ AppNotifier notifier,+ String machineId,+ String agentId,+ String name, {+ AppKeymap? keymap,+}) => showTerminalPrompt<void>(+ context,+ keymap: keymap,+ builder: (_) => _DeleteHarnessPrompt(+ notifier: notifier,+ machineId: machineId,+ agentId: agentId,+ name: name,+ ),+);++class _DeleteHarnessPrompt extends StatefulWidget {+ const _DeleteHarnessPrompt({+ required this.notifier,+ required this.machineId,+ required this.agentId,+ required this.name,+ });+ final AppNotifier notifier;+ final String machineId, agentId, name;+ @override+ State<_DeleteHarnessPrompt> createState() => _DeleteHarnessPromptState();+}++class _DeleteHarnessPromptState extends State<_DeleteHarnessPrompt> {+ final _cancel = FocusNode(debugLabel: 'Cancel delete');+ final _promptFocus = FocusNode(debugLabel: 'Pending delete');+ final _body = ScrollController();+ final _announcer = BoxAnnouncer();+ bool _deleting = false;+ String? _error;++ @override+ void initState() {+ super.initState();+ _focusCancel();+ }++ void _focusCancel() => WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {+ _cancel.requestFocus();+ }+ });++ @override+ void dispose() {+ _cancel.dispose();+ _promptFocus.dispose();+ _body.dispose();+ super.dispose();+ }++ void _close() => Navigator.pop(context);+ void _page(int direction) {+ if (!_body.hasClients) return;+ final position = _body.position;+ _body.jumpTo(+ (position.pixels + direction * position.viewportDimension * .8).clamp(+ position.minScrollExtent,+ position.maxScrollExtent,+ ),+ );+ }++ Future<void> _delete() async {+ if (_deleting) return;+ _promptFocus.requestFocus();+ setState(() {+ _deleting = true;+ _error = null;+ });+ String? error;+ try {+ error = await widget.notifier.purgeAgent(+ widget.machineId,+ widget.agentId,+ );+ } catch (_) {+ error = 'Could not delete the harness. Try again.';+ }+ if (!mounted) return;+ if (error == null) {+ Navigator.pop(context);+ return;+ }+ setState(() {+ _deleting = false;+ _error = error;+ });+ _announcer.row(context, error);+ _focusCancel();+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final danger = Theme.of(context).colorScheme.error;+ final closeLabel = _deleting ? 'Close' : 'Cancel';+ return TerminalPromptKeys(+ focusNode: _promptFocus,+ cancel: _close,+ pageDown: () => _page(1),+ pageUp: () => _page(-1),+ child: DesktopPromptSurface(+ body: DesktopPromptScrollBody(+ controller: _body,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text('Delete Harness', style: DesktopChrome.heading()),+ const SizedBox(height: DesktopChrome.groupGap),+ Text(+ widget.name,+ style: DesktopChrome.text(size: 14, medium: true),+ ),+ if (widget.notifier+ .stateOf(widget.machineId)+ ?.machine+ .displayName+ case final machine?) ...[+ const SizedBox(height: 4),+ Text(machine, style: DesktopChrome.metadata()),+ ],+ const SizedBox(height: DesktopChrome.groupGap),+ Text(+ 'Delete this harness and its saved conversation? It stops if '+ 'running, and it cannot be opened again. Project files are kept.',+ style: DesktopChrome.text(size: 13),+ ),+ const SizedBox(height: 8),+ Text(+ 'To keep the conversation to reopen later, use Stop Harness instead.',+ style: DesktopChrome.text(size: 13, color: DesktopChrome.muted),+ ),+ ],+ ),+ ),+ footer: _error != null || _deleting+ ? Semantics(+ liveRegion: true,+ child: DesktopPromptMessage(+ _error ?? 'Deleting…',+ color: _error == null ? DesktopChrome.muted : danger,+ ),+ )+ : null,+ actions: [+ Tooltip(+ message:+ '$closeLabel · ${terminalPromptHint(context, 'picker.cancel', 'esc')}',+ child: TextButton(+ focusNode: _deleting ? null : _cancel,+ onPressed: _close,+ child: Text(closeLabel),+ ),+ ),+ if (!_deleting)+ Tooltip(+ message:+ 'Delete · ${terminalPromptHint(context, 'picker.accept', 'enter')}',+ child: FilledButton(+ key: const Key('agent-delete-confirm'),+ onPressed: () => unawaited(_delete()),+ style: grid.dangerButtonStyle(),+ child: const Text('Delete'),+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex 5fa94c703..11095b2a6 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -171,6 +171,7 @@ class SwarmSearchKeys extends StatelessWidget {this.onNewAgent,this.onCommands,this.onRefocus,+ this.onDelete,this.previewControls,this.desktop = false,required this.child,@@ -186,6 +187,9 @@ class SwarmSearchKeys extends StatelessWidget {final VoidCallback? onNewAgent;final VoidCallback? onCommands;final VoidCallback? onRefocus;++ /// Delete Harness for the selected row (`picker.delete`), when it is one.+ final ValueChanged<SwarmDestination>? onDelete;final SearchPreviewControls? previewControls;final bool desktop;final Widget child;@@ -277,6 +281,13 @@ class SwarmSearchKeys extends StatelessWidget {'picker.preview_down': () => run(() => search.scrollPreview(1)),'picker.preview_page_up': () => run(() => search.page(-1)),'picker.preview_page_down': () => run(() => search.page(1)),+ if (onDelete != null)+ 'picker.delete': () => run(() {+ if (search.selected case final row?+ when row.agentId != null && row.machineId != null) {+ onDelete!(row);+ }+ }),},'picker.cancel': dismiss,'picker.complete': () => complete(true),diff --git a/desktop/test/agent_purge_state_test.dart b/desktop/test/agent_purge_state_test.dartnew file mode 100644index 000000000..ca0349615--- /dev/null+++ b/desktop/test/agent_purge_state_test.dart@@ -0,0 +1,74 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';++import 'support/rename_connection.dart';+import 'swarm_state_test.dart' show createApp;+import 'swarm_screen_test.dart' show terminal;++/// The daemon's reviewed deletion: `inspect` answers a review, `delete` acts on it.+class PurgeConnection extends RenameConnection {+ final purges = <Map<String, dynamic>>[];+ Map<String, dynamic> inspectReply = {'reviewId': 'review-1', 'sessionBytes': 1024};+ Map<String, dynamic> deleteReply = {'deleted': true, 'sessionDeleted': true};++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) {+ if (type == 'agent_purge') {+ purges.add(payload);+ return Future.value(payload['mode'] == 'inspect' ? inspectReply : deleteReply);+ }+ return super.request(type, payload: payload, timeout: timeout);+ }+}++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ late PurgeConnection connection;+ late AppNotifier app;+ final created = DateTime.utc(2026, 10, 14, 3, 53, 20, 610);+ setUp(() {+ connection = PurgeConnection();+ app = createApp(connectionForTest: (_) => connection);+ });+ tearDown(() => app.dispose());++ test('Delete Harness reviews, then deletes under that review, and the harness leaves the list', () async {+ app.stateOf('m')!.agents = [+ Agent(id: 'a0', name: 'Codex', engine: 'codex', sessionId: 's0', createdAt: created, status: 'stopped'),+ ];+ final pane = app.adoptSessionForTest(terminal('a0', []));+ expect(await app.purgeAgent('m', 'a0'), isNull);+ expect(connection.purges, [+ {'agentId': 'a0', 'sessionId': 's0', 'createdAt': created.millisecondsSinceEpoch, 'mode': 'inspect'},+ {'agentId': 'a0', 'sessionId': 's0', 'createdAt': created.millisecondsSinceEpoch, 'mode': 'delete', 'reviewId': 'review-1'},+ ]);+ expect(app.stateOf('m')!.agents.any((a) => a.id == 'a0'), isFalse);+ expect(app.allPanes, isNot(contains(pane)));+ });++ test('a harness that never bound a conversation is named by no session', () async {+ app.stateOf('m')!.agents = [Agent(id: 'a0', name: 'Codex', engine: 'codex', createdAt: created)];+ expect(await app.purgeAgent('m', 'a0'), isNull);+ expect(connection.purges.first['sessionId'], isNull);+ });++ test('a refused review deletes nothing and says why', () async {+ app.stateOf('m')!.agents = [Agent(id: 'a0', name: 'Codex', engine: 'codex', sessionId: 's0', createdAt: created)];+ connection.inspectReply = {'error': 'DELETE_REFUSED', 'detail': 'Another harness uses this conversation.'};+ expect(await app.purgeAgent('m', 'a0'), 'Delete failed: Another harness uses this conversation.');+ expect(connection.purges.map((p) => p['mode']), ['inspect']);+ expect(app.stateOf('m')!.agents.any((a) => a.id == 'a0'), isTrue);+ });++ test('a delete that is not confirmed keeps the harness listed', () async {+ app.stateOf('m')!.agents = [Agent(id: 'a0', name: 'Codex', engine: 'codex', sessionId: 's0', createdAt: created)];+ connection.deleteReply = {};+ expect(await app.purgeAgent('m', 'a0'), contains('Could not confirm the deletion'));+ expect(app.stateOf('m')!.agents.any((a) => a.id == 'a0'), isTrue);+ });+}