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.

Add Harnesses activity manager with safe pause and resume (#236)

Dee1cb238f99ee9
diff --git a/artifacts/harness-manager/harnesses.png b/artifacts/harness-manager/harnesses.png
new file mode 100644
index 000000000..1b425433f
Binary files /dev/null and b/artifacts/harness-manager/harnesses.png differ
diff --git a/artifacts/harness-manager/minimize.png b/artifacts/harness-manager/minimize.png
new file mode 100644
index 000000000..893e09f28
Binary files /dev/null and b/artifacts/harness-manager/minimize.png differ
diff --git a/artifacts/harness-manager/needs-input.png b/artifacts/harness-manager/needs-input.png
new file mode 100644
index 000000000..c292793f4
Binary files /dev/null and b/artifacts/harness-manager/needs-input.png differ
diff --git a/artifacts/harness-manager/validation.md b/artifacts/harness-manager/validation.md
new file mode 100644
index 000000000..b6df40636
--- /dev/null
+++ b/artifacts/harness-manager/validation.md
@@ -0,0 +1,69 @@
+# Harness manager validation
+
+Verified September 22, 2026. [Harnesses](harnesses.png) · [Needs input](needs-input.png) · [Minimize keyframe](minimize.png).
+
+All process tests used newly created Claude and Codex harnesses with temporary
+profiles, synthetic conversation history, and private tmux servers. No existing
+user harness was paused, stopped, or restarted. Native engines used a local test
+provider; the checks did not require paid model requests.
+
+| Check | Result |
+| --- | --- |
+| Native Mac app and CLI builds | Passed |
+| Flutter analysis and CLI type checking | Passed |
+| Desktop manager, lifecycle, navigation, shortcuts, and terminal regressions | 131 passed, including the rendered preview |
+| Lifecycle suite | 200 passed; 100% statements, branches, functions, and lines in the five covered lifecycle modules |
+| Related CLI transport, activity timestamps, process, and terminal regressions | 188 passed |
+| Native AppKit titlebar checks | 472 passed with the File-menu PR |
+| Native Claude and Codex lifecycle fixtures | Passed, including three immediate pause/resume cycles per engine |
+| Native Mac UI acceptance | Passed, including three manager pause/resume cycles per engine, repeated clicks, background resume, pane reopening, and original history |
+| Final visual render | Passed |
+
+The suites overlap; these counts are not a combined total. The optional visual
+render is enabled in the reported desktop run. It is skipped in ordinary runs.
+
+The final integration with the other recent PRs passed the full desktop suite
+(2,821 passed, 11 skipped), analysis of all changed Dart files, and a fresh macOS
+build. A separate render run passed all 23 manager checks. This pass caught and
+fixed delayed input handoff during minimization and clipped keyboard selection
+in long lists. The combined CLI run passed 3,998 tests with 63 skipped; one
+timing-sensitive offline hook test failed under load, then its complete file
+passed all 31 checks in isolation. CLI type checking also passed.
+
+Verified safeguards include confirmed process termination before reporting pause,
+exact-pane closure that preserves neighboring panes, conversation identity across
+registry reloads, duplicate-operation prevention, retained rows after refresh
+failure, and actionable native errors. A late hook may rebuild a registry record
+without falsely appearing to replace its process; changed process, conversation,
+or terminal identities still reject the operation.
+
+Pane minimization uses a bounded GPU snapshot and a curved mesh. Closing releases
+keyboard input immediately; only the captured pixels continue moving, without
+resizing or stopping the departing process.
+Keyframes were rendered and the animation was exercised in the native preview.
+Keyboard navigation, machine search, activity sorting and compact ages, current and
+replaced questions, separate accessible open/control actions, small windows, larger
+text, and Reduce Motion are covered. The clock stays on the context line; only a
+waiting harness adds a help action beside pause/play. The former bell and its
+shortcut now open Needs input in this same manager. A numbered badge appears at
+the icon’s top right only for pending questions; large counts use `99+`.
+
+Pause/resume controls currently support saved Claude and Codex conversations on
+both local and connected remote machines. Commands go to the owning machine's
+daemon; shared machines are view-only.
+Other engines remain viewable with a tooltip explaining that exact resume is
+unavailable. The built app and CLI were not installed over or used to restart the
+user's running app or daemon.
+
+Key repeatable checks are `npm run test:resume` and `npm run test:resume-native`
+from `cli`, and `flutter test test/harness_session_manager_test.dart
+test/agent_pause_state_test.dart` from `desktop`. The native Mac test is
+`desktop/integration_test/native_resume_e2e_test.dart`; its header documents the
+private fixture setup.
+
+The native integration test lets macOS own accessibility activation instead of
+retaining a test-only semantics handle across window deactivation. This avoids a
+Flutter engine bridge reset receiving a partial tree as its first update; ordinary
+widget tests still verify VoiceOver actions with semantics enabled. The native
+suite completed in 26 seconds after this correction. Fixture cleanup rescans for
+shell history files written during shutdown.
diff --git a/cli/scripts/resume-native-e2e.ts b/cli/scripts/resume-native-e2e.ts
index 04880bb8e..7d0f0b945 100644
--- a/cli/scripts/resume-native-e2e.ts
+++ b/cli/scripts/resume-native-e2e.ts
@@ -99,7 +99,7 @@ try {
{ timestamp, type: 'event_msg', payload: { type: 'agent_message', message: `Retained ${marker}`, phase: 'final_answer' } },
{ timestamp, type: 'event_msg', payload: { type: 'task_complete', turn_id: sessionId, last_agent_message: `Retained ${marker}` } },
].map(row => JSON.stringify(row)).join('\n') + '\n')
- writeFileSync(join(profile, 'config.toml'), `model_provider = "fixture"\n[model_providers.fixture]\nname = "Local fixture"\nbase_url = "http://127.0.0.1:9/v1"\nwire_api = "responses"\nrequires_openai_auth = false\n[projects.${JSON.stringify(cwd)}]\ntrust_level = "trusted"\n[features]\nhooks = true\n`)
+ writeFileSync(join(profile, 'config.toml'), `model_provider = "fixture"\ncheck_for_update_on_startup = false\n[model_providers.fixture]\nname = "Local fixture"\nbase_url = "http://127.0.0.1:9/v1"\nwire_api = "responses"\nrequires_openai_auth = false\n[projects.${JSON.stringify(cwd)}]\ntrust_level = "trusted"\n[features]\nhooks = true\n`)
installCodexHooks(server.port, profile)
}
@@ -133,7 +133,7 @@ try {
const stopJobs = new Map<string, Promise<void>>()
socketBackend.onDeleteAgent = createStopAgentService({
registry, stoppedAgents, restartJobs: jobs, stopJobs, tmuxBackend: backend,
- agentReconciler: { suppress: () => {}, trigger: async () => {} },
+ agentReconciler: { suppress: () => {}, holdRoute: () => {}, releaseRoute: () => {}, trigger: async () => {} },
forgetSession: id => registry.removeAgent(id), markDeleted: () => {}, clearDeleted: () => {},
})
socketBackend.onResumeAgent = createResumeAgentService({
@@ -183,6 +183,8 @@ try {
const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', live.tmuxPane)
assert(screen.includes(marker), 'restored conversation text must be visible')
const pid = live.processIdentity!.pid; const route = live.tmuxPane
+ const neighbour = (await tmux('split-window', '-d', '-P', '-F', '#{pane_id}', '-t', route, '/bin/sh')).trim()
+ const neighbourPid = (await tmux('display-message', '-p', '-t', neighbour, '#{pane_pid}')).trim()
assert.equal((await checkSessionRuntime(live)).state, 'alive')
assert.equal((await rpc('agent_resume', { agentId: old.agentId, creationId: randomUUID() })).resumed, true)
assert.equal(registry.byAgent(old.agentId)!.processIdentity!.pid, pid); assert.equal(registry.byAgent(old.agentId)!.tmuxPane, route)
@@ -202,6 +204,8 @@ try {
// Stop uses a known fixture-owned tmux session; its saved row survives a registry reload.
assert.equal((await rpc('agent_delete', { agentId: live.agentId })).deleted, true)
assert.equal((await checkPidRuntime(live)).state, 'gone')
+ assert.equal((await tmux('display-message', '-p', '-t', neighbour, '#{pane_pid}')).trim(), neighbourPid,
+ 'Stop must preserve unrelated work in another pane of the same tmux session')
registry.load(); assert(!registry.byAgent(old.agentId)); assert.equal(stoppedAgents.get(old.agentId)!.sessionId, sessionId)
assert((await rpc('agents_list', { includeStopped: true })).agents.some((a: any) => a.id === old.agentId && a.status === 'stopped'))
const reopened = await openSaved(randomUUID())
@@ -232,7 +236,15 @@ try {
assert.equal((await tmux('display-message', '-p', '-t', exited.tmuxPane, '#{pane_pid}')).trim(), shellPid)
assert((await tmux('capture-pane', '-p', '-t', exited.tmuxPane)).includes(shellMarker))
assert.equal((await rpc('agent_delete', { agentId: old.agentId })).deleted, true)
- log(`PASS ${engine}: native history + hook, new tmux runtime, same id, attach same PID, receipt replay, missing-ID recovery before Stop, stop persistence, surviving shell preserved`)
+ for (let cycle = 0; cycle < 3; cycle++) {
+ assert.equal((await openSaved(randomUUID())).state, 'created')
+ const current = registry.byAgent(old.agentId)!
+ assert.equal(current.sessionId, sessionId)
+ const paused = await rpc('agent_delete', { agentId: old.agentId })
+ assert.equal(paused.deleted, true, JSON.stringify(paused))
+ assert.equal((await checkPidRuntime(current)).state, 'gone')
+ }
+ log(`PASS ${engine}: native history + hook, three immediate pause/resume cycles, new tmux runtime, same id, attach same PID, receipt replay, missing-ID recovery before Stop, stop persistence, neighbouring pane and surviving shell preserved`)
}
if (process.argv.includes('--serve')) {
// The desktop acceptance test uses the real local WS transport and terminal streams.
@@ -283,7 +295,12 @@ try {
const stop = socketBackend.onDeleteAgent!
socketBackend.onDeleteAgent = async id => {
assert(fixtures.some(f => f.agentId === id), 'never stop the anchor or a non-fixture session')
- await stop(id)
+ const before = JSON.stringify(registry.byAgent(id))
+ try { await stop(id) }
+ catch (error) {
+ console.error('[resume-native] native pause failed:', error, { before, after: JSON.stringify(registry.byAgent(id)) })
+ throw error
+ }
socketBackend.send({ type: 'agent_deleted', payload: { agentId: id, retained: true } })
}
let finish!: () => void
@@ -303,6 +320,8 @@ try {
assert.equal(row.sessionId, fixture.sessionId)
const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', row.tmuxPane)
assert(screen.includes(fixture.marker), 'native terminal must show original history')
+ } else {
+ assert.equal((await checkPidRuntime(saved!)).state, 'gone', 'Paused must mean the original process is gone')
}
const persisted = JSON.parse(readFileSync(join(root, 'data', 'registry.json'), 'utf8'))
assert.equal(persisted.some((r: any) => r.agentId === id), !!row)
@@ -327,5 +346,15 @@ try {
await socketBackend.stop()
// Keep fixture diagnostics when requested; contains only synthetic history, no credentials.
if (process.env.KEEP_RESUME_FIXTURE === '1') log(`fixture: ${root}`)
- else rmSync(root, { recursive: true, force: true })
+ else {
+ // A shell can flush .zsh_history just after tmux exits. Retry the whole walk,
+ // not only rmdir, so a late-created file is discovered and removed as well.
+ for (let attempt = 0; ; attempt++) {
+ try { rmSync(root, { recursive: true, force: true }); break }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOTEMPTY' || attempt === 5) throw error
+ await new Promise(resolve => setTimeout(resolve, 100))
+ }
+ }
+ }
}
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index e4f7437e0..6b126797e 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -9,6 +9,7 @@ import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js'
import { registry, type RegisteredSession } from './lib/registry.js'
import { stoppedAgents } from './lib/stoppedAgents.js'
+import { AgentStopError } from './lib/stopAgentService.js'
import * as mediaPreview from './lib/mediaPreview.js'
import * as gitProject from './lib/gitProject.js'
import * as projectFolder from './lib/projectFolder.js'
@@ -18,6 +19,25 @@ import { randomUUID } from 'node:crypto'
import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixtures__/fakeGrid.js'
import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
+describe('confirmed harness pause replies', () => {
+ it.each(['unsupported', 'unconfirmed', 'confirmed'] as const)('%s stop never sends a false success', async state => {
+ const socket = new BackendSocket('fixture')
+ const frames: any[] = []
+ socket.registerLocalClient('local:pause', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })
+ if (state !== 'unsupported') socket.onDeleteAgent = async () => {
+ if (state === 'unconfirmed') throw new AgentStopError('The process could not be verified.')
+ }
+ await (socket as any).dispatchDown({ type: 'agent_delete', payload: { requestId: 'pause', agentId: 'fixture' } }, 'local:pause')
+ const reply = frames.find(frame => frame.type === 'agent_delete_result')?.payload
+ expect(reply).toMatchObject(state === 'confirmed' ? { deleted: true } : {
+ error: state === 'unsupported' ? 'UNSUPPORTED' : 'STOP_UNCONFIRMED',
+ })
+ if (state !== 'confirmed') expect(reply.deleted).toBeUndefined()
+ if (state === 'unconfirmed') expect(reply.detail).toBe('The process could not be verified.')
+ await socket.stop()
+ })
+})
+
describe('viewer forwarding authentication', () => {
it('requires encryption and a web-role session remotely, while permitting trusted local clients', async () => {
const socket = new BackendSocket('token')
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index e3a1b701c..ec3d02266 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -26,6 +26,7 @@ import { env } from './config/env.js'
import { AuthSessionManager, AuthSessionError } from './lib/authSession.js'
import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
+import { AgentStopError } from './lib/stopAgentService.js'
import { ENGINES, PROCESS_ENGINES, isTerminalEngine, type AgentEngine, type ProcessEngine } from './engines/types.js'
import { listDir } from './lib/fsBrowse.js'
import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'
@@ -2298,7 +2299,13 @@ export class BackendSocket {
case 'agent_delete': {
const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
- await this.onDeleteAgent?.(target)
+ if (!this.onDeleteAgent) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }
+ try { await this.onDeleteAgent(target) }
+ catch (error) {
+ if (!(error instanceof AgentStopError)) throw error
+ reply(type, requestId, { error: error.code, detail: error.message })
+ return
+ }
reply(type, requestId, { deleted: true })
return
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 53c57cb6e..2ef1d3ba9 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -4943,7 +4943,7 @@ async function runForeground(session: AuthSession): Promise<void> {
/**
* Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live
- * registry entry, and kills its containing tmux session. Exact PID/start-marker validation guards the engine's
+ * registry entry, and closes only its exact tmux pane. Exact PID/start-marker validation guards the engine's
* SIGTERM/SIGKILL fallback. Engine conversation files, recaps and the Harness name remain on disk.
*/
const stopJobs = new Map<string, Promise<void>>()
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
index 2457c896d..bf924c237 100644
--- a/cli/src/lib/resumeAgentService.spec.ts
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -229,6 +229,12 @@ describe('existing runtime and readiness verification', () => {
const result = start(); await vi.advanceTimersByTimeAsync(500)
expect(await result).toMatchObject({ ok: true }); expect(resolvePaneEngineProcess).toHaveBeenCalledTimes(2)
})
+ it('honors a stop requested as the newly allocated runtime is announced', async () => {
+ vi.mocked(deps.announceSession).mockImplementation(() => deps.restartJobs.cancel(saved.agentId))
+ expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' })
+ expect(deps.stoppedAgents.get(saved.agentId)?.sessionId).toBe(saved.sessionId)
+ expect(deps.stoppedAgents.beginResume(saved.agentId)).toBeNull()
+ })
it.each([true, false])('cancels while clearing remain-on-exit, terminal=%s', async terminal => {
if (terminal) rewrite({ engine: 'terminal', sessionId: '', transcriptPath: '' })
vi.mocked(clearPaneRemainOnExit).mockImplementation(async () => { deps.restartJobs.cancel(saved.agentId) })
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index 3eb9e2255..09c6ea247 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -45,8 +45,8 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
// readiness probe would return it straight back. The desk sees the tile leave "Start failed".
const unconfirmed = ownsRoute() ? registry.byAgent(saved.agentId) : undefined
if (unconfirmed?.launch?.state === 'failed' && unconfirmed.launch.error === 'RESUME_UNCONFIRMED') {
- const starting = registry.setLaunch(saved.agentId, { state: 'starting' })
- if (starting) announceSession(starting)
+ // No await separates the verified row above from this synchronous update.
+ announceSession(registry.setLaunch(saved.agentId, { state: 'starting' })!)
}
const result = await waitForResumedAgent(saved, {
current: ownsRoute,
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
index 577331b87..9cf238ef4 100644
--- a/cli/src/lib/stopAgentService.spec.ts
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -16,7 +16,7 @@ beforeEach(() => {
Object.assign(row, { sessionId: 'saved', processIdentity: { pid: 77, executable: 'codex', startMarker: 'fixture' } })
deps = { registry, stoppedAgents, restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(),
tmuxBackend: { kill: vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })) },
- agentReconciler: { suppress: vi.fn(), trigger: vi.fn(async () => {}) },
+ agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },
forgetSession: vi.fn(id => registry.removeAgent(id)), markDeleted: vi.fn(), clearDeleted: vi.fn(),
}
vi.mocked(terminateDeletedAgent).mockResolvedValue('gone')
@@ -46,10 +46,83 @@ it.each(['terminal', 'without tmux', 'failed process', 'failed tmux'] as const)(
if (mode === 'without tmux') { deps.tmuxBackend = null; row.runtimes = [{ backend: 'herdr', endpointId: 'fixture', paneId: '1' } as any] }
if (mode === 'failed process') vi.mocked(terminateDeletedAgent).mockResolvedValue('failed')
if (mode === 'failed tmux') vi.mocked(deps.tmuxBackend!.kill).mockResolvedValue({ state: 'unknown', dispatch: 'possibly_executed', reason: 'fixture' })
- await createStopAgentService(deps)(row.agentId)
+ const stopping = createStopAgentService(deps)(row.agentId)
+ if (mode === 'failed process' || mode === 'failed tmux') {
+ await expect(stopping).rejects.toThrow('Could not confirm')
+ expect(registry.byAgent(row.agentId)).toBe(row)
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+ expect(deps.agentReconciler.suppress).not.toHaveBeenCalled()
+ } else await stopping
expect(stoppedAgents.get(row.agentId)).not.toBeNull(); expect(deps.agentReconciler.trigger).toHaveBeenCalledOnce()
expect(stoppedAgents.beginResume(row.agentId) === null).toBe(mode === 'failed process' || mode === 'failed tmux')
})
+
+it('does not publish a stopped row until the exact process and terminal have both stopped', async () => {
+ let finishProcess!: () => void
+ let finishPane!: () => void
+ vi.mocked(terminateDeletedAgent).mockImplementation(() => new Promise(resolve => { finishProcess = () => resolve('terminated') }))
+ vi.mocked(deps.tmuxBackend!.kill).mockImplementation(() => new Promise(resolve => { finishPane = () => resolve({ state: 'succeeded', dispatch: 'executed' }) }))
+ const stop = createStopAgentService(deps)
+ const stopping = stop(row.agentId)
+ await vi.waitFor(() => expect(finishProcess).toBeTypeOf('function'))
+ expect(registry.byAgent(row.agentId)).toBe(row)
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+ finishPane()
+ await Promise.resolve()
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+ expect(stop(row.agentId)).toBe(stopping)
+ finishProcess()
+ await stopping
+ expect(deps.forgetSession).toHaveBeenCalledOnce()
+ expect(deps.agentReconciler.holdRoute).toHaveBeenCalledOnce()
+ expect(deps.agentReconciler.releaseRoute).toHaveBeenCalledOnce()
+})
+
+it.each(['process', 'pane'] as const)('a rejected %s check retains history, releases its route and permits a safe retry', async side => {
+ if (side === 'process') vi.mocked(terminateDeletedAgent).mockRejectedValueOnce(new Error('probe failed'))
+ else vi.mocked(deps.tmuxBackend!.kill).mockRejectedValueOnce(new Error('transport failed'))
+ const stop = createStopAgentService(deps)
+ await expect(stop(row.agentId)).rejects.toThrow('Could not confirm')
+ expect(deps.stopJobs.size).toBe(0)
+ expect(registry.byAgent(row.agentId)).toBe(row)
+ expect(deps.agentReconciler.releaseRoute).toHaveBeenCalledOnce()
+ expect(deps.clearDeleted).toHaveBeenCalledWith(row.agentId)
+ await stop(row.agentId)
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+})
+
+it.each(['no backend', 'no tmux route'] as const)('cannot confirm stopping a shell with %s', async mode => {
+ row.engine = 'terminal'
+ if (mode === 'no backend') deps.tmuxBackend = null
+ else row.runtimes = [{ backend: 'herdr', endpointId: 'fixture', paneId: '1' } as any]
+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('Could not confirm')
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+})
+
+it.each(['removed', 'replaced', 'conversation', 'route'] as const)('does not remove a target %s during termination', async mode => {
+ vi.mocked(terminateDeletedAgent).mockImplementation(async () => {
+ if (mode === 'removed') registry.removeAgent(row.agentId)
+ else if (mode === 'conversation') row.sessionId = 'different-conversation'
+ else if (mode === 'route') row.runtimes = [{ backend: 'tmux', paneId: '%88' }]
+ else row.processIdentity = { ...row.processIdentity!, pid: 88 }
+ return 'terminated'
+ })
+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('changed while pausing')
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+})
+it.each(['capture', 'termination'] as const)('accepts a hook rebuilding the same process during %s', async stage => {
+ const replacement = { ...row, title: 'Updated title',
+ processIdentity: { startMarker: 'fixture', executable: 'codex', pid: 77 },
+ runtimes: row.runtimes.map(runtime => ({ ...runtime })),
+ }
+ const rebuild = () => { vi.spyOn(registry, 'resolve').mockReturnValue(replacement) }
+ if (stage === 'capture') vi.mocked(captureResumeIdentity).mockImplementation(async session => { rebuild(); return session })
+ else vi.mocked(terminateDeletedAgent).mockImplementation(async () => { rebuild(); return 'terminated' })
+ await createStopAgentService(deps)(row.agentId)
+ expect(deps.forgetSession).toHaveBeenCalledExactlyOnceWith(row.agentId, { force: true })
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+ expect(stoppedAgents.get(row.agentId)?.sessionId).toBe('saved')
+})
it('only signals through the validated process deleter and does not erase a newer stop job', async () => {
const signal = vi.spyOn(process, 'kill').mockReturnValue(true)
vi.mocked(terminateDeletedAgent).mockImplementation(async (entry, actions) => {
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index 36f76a9d8..64dd444da 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -6,6 +6,7 @@ import type { StoppedAgentStore } from './stoppedAgents.js'
import type { AgentRestartCoordinator } from './restartAgent.js'
import type { TerminalBackend } from './terminalBackend.js'
import type { TmuxRuntimeRef } from './terminalTypes.js'
+import { terminalRouteKey } from './terminalRuntime.js'
import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.js'
export interface StopAgentServiceDeps {
@@ -14,11 +15,28 @@ export interface StopAgentServiceDeps {
restartJobs: AgentRestartCoordinator
stopJobs: Map<string, Promise<void>>
tmuxBackend: Pick<TerminalBackend<TmuxRuntimeRef>, 'kill'> | null
- agentReconciler: { suppress(session: RegisteredSession): void; trigger(): Promise<unknown> }
+ agentReconciler: {
+ suppress(session: RegisteredSession): void
+ holdRoute(route: string): void
+ releaseRoute(route: string): void
+ trigger(): Promise<unknown>
+ }
forgetSession(agentId: string, options: { force: true }): void
markDeleted(agentId: string): void
clearDeleted(agentId: string): void
}
+export class AgentStopError extends Error {
+ readonly code = 'STOP_UNCONFIRMED'
+}
+
+// Hooks rebuild registry objects. Compare stable values, never JavaScript object
+// identity or property ordering, while retaining the exact PID-reuse guard.
+const runtimeIdentity = (entry: RegisteredSession | undefined) => entry ? JSON.stringify([
+ entry.engine, entry.registeredAt, entry.processIdentity?.pid,
+ entry.processIdentity?.executable, entry.processIdentity?.startMarker,
+ entry.runtimes.map(terminalRouteKey).sort(),
+]) : null
+
export function createStopAgentService(deps: StopAgentServiceDeps) {
const { registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,
forgetSession, markDeleted, clearDeleted } = deps
@@ -30,40 +48,62 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
const job = Promise.resolve().then(async () => {
const live = registry.resolve(sessionId)
if (!live) return
- const identity = JSON.stringify([live.engine, live.processIdentity, live.runtimes])
+ const identity = runtimeIdentity(live)
+ const conversation = live.sessionId
+ const sameTarget = () => {
+ const current = registry.resolve(sessionId)
+ return runtimeIdentity(current) === identity && (!conversation || current!.sessionId === conversation)
+ }
const captured = await captureResumeIdentity({ ...live })
// Discovery or a hook may have updated this row while reading the native store.
// A replacement process must never be stopped using an older snapshot.
- if (registry.resolve(sessionId) !== live
- || JSON.stringify([live.engine, live.processIdentity, live.runtimes]) !== identity) {
- throw new Error('Harness changed while saving its conversation. Try Stop again.')
+ if (!sameTarget()) {
+ throw new AgentStopError('Harness changed while saving its conversation. Try pausing again.')
}
- const s = live.sessionId && live.sessionId !== captured.sessionId ? { ...live } : { ...live, sessionId: captured.sessionId,
+ const current = registry.resolve(sessionId)!
+ const s = current.sessionId && current.sessionId !== captured.sessionId ? { ...current } : { ...current, sessionId: captured.sessionId,
transcriptPath: captured.transcriptPath, boundAt: captured.boundAt, source: captured.source }
// Saving precedes every mutation. A storage failure leaves the live agent alone.
stoppedAgents.save(s)
- markDeleted(sessionId)
- if (s.sessionId) markDeleted(s.sessionId)
- if (s.processIdentity) agentReconciler.suppress(s)
- forgetSession(sessionId, { force: true })
- const paneStop = tmuxBackend
- ? Promise.all(s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
- .map(runtime => tmuxBackend!.kill(runtime)))
- : Promise.resolve([])
- const processStop = isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
- : terminateDeletedAgent(s, {
- checkRuntime: checkPidRuntime,
- kill: (pid, signal) => process.kill(pid, signal),
- sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
- log: message => console.log(message),
- }, 0)
- const [paneOutcomes, outcome] = await Promise.all([paneStop, processStop])
- if (outcome !== 'failed') {
- if (paneOutcomes.every(result => result.state === 'succeeded')) stoppedAgents.finishResume(sessionId)
+ const routes = s.runtimes.map(terminalRouteKey)
+ for (const route of routes) agentReconciler.holdRoute(route)
+ try {
+ markDeleted(sessionId)
+ if (s.sessionId) markDeleted(s.sessionId)
+ const paneStop = tmuxBackend
+ ? Promise.all(s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
+ .map(runtime => tmuxBackend!.kill(runtime)))
+ : Promise.resolve([])
+ const processStop = isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
+ : terminateDeletedAgent(s, {
+ checkRuntime: checkPidRuntime,
+ kill: (pid, signal) => process.kill(pid, signal),
+ sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
+ log: message => console.log(message),
+ }, 0)
+ // Both checks must settle before releasing the route or permitting a retry.
+ const [panes, termination] = await Promise.allSettled([paneStop, processStop])
+ if (panes.status !== 'fulfilled' || termination.status !== 'fulfilled'
+ || termination.value === 'failed'
+ || panes.value.some(result => result.state !== 'succeeded')
+ || (isTerminalEngine(s.engine) && (!tmuxBackend || !panes.value.length))) {
+ throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try pausing again.')
+ }
+ // Never remove a replacement discovered while the process checks were awaiting.
+ if (!sameTarget()) {
+ throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')
+ }
+ stoppedAgents.finishResume(sessionId)
+ if (s.processIdentity) agentReconciler.suppress(s)
+ // This publishes agent_deleted. It must follow confirmed termination, or a
+ // desktop can display Paused and allow Resume while the old process runs.
+ forgetSession(sessionId, { force: true })
+ } finally {
clearDeleted(sessionId)
if (s.sessionId) clearDeleted(s.sessionId)
+ for (const route of routes) agentReconciler.releaseRoute(route)
+ void agentReconciler.trigger()
}
- void agentReconciler.trigger()
}).finally(() => {
if (stopJobs.get(sessionId) === job) stopJobs.delete(sessionId)
})
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index e80bb570c..7c0315f44 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -14,7 +14,7 @@ afterEach(() => {
})
describe('TmuxBackend lifecycle', () => {
- it('creates a detached session and kills the session resolved from its root pane', async () => {
+ it('creates a detached session and closes only its exact pane', async () => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-lifecycle-'))
dirs.push(dir)
const calls = join(dir, 'calls')
@@ -45,11 +45,31 @@ esac
// terminal for its colours (OSC 10/11) once, at startup, and never again.
'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -w remain-on-exit on ; set-option -w window-style bg=#181818,fg=#f5f5f5',
'set-option -t %42 mouse on',
- 'display-message -p -t %42 #{session_id}',
- 'kill-session -t $7',
+ 'kill-pane -t %42',
])
})
+ it.each(['gone', 'present', 'unknown', 'malformed', 'no server'] as const)('verifies %s inventory after a failed pane-close reply', async mode => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-close-'))
+ dirs.push(dir)
+ const inventory = mode === 'gone' ? "printf '%%43\\n'" : mode === 'present' ? "printf '%%42\\n'"
+ : mode === 'malformed' ? "printf 'not a pane\\n'" : mode === 'no server'
+ ? "printf 'no server running on /tmp/fixture\\n' >&2; exit 1" : 'exit 1'
+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh\nif [ "$1" = list-panes ]; then\n${inventory}\nelse\nexit 1\nfi\n`, { mode: 0o700 })
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ const backend = new TmuxBackend()
+ // Even if discovery hides this pane (e.g. its session was renamed), the
+ // exact-pane check must see it and refuse a false successful pause.
+ const discovery = vi.spyOn(backend, 'inventory').mockResolvedValue({ state: 'available', roots: [] })
+ expect((await backend.kill({ backend: 'tmux', paneId: '%42' })).state).toBe(mode === 'gone' || mode === 'no server' ? 'succeeded' : 'unknown')
+ expect(discovery).not.toHaveBeenCalled()
+ })
+
+ it('rejects broad tmux targets before executing a command', async () => {
+ const backend = new TmuxBackend()
+ expect(await backend.kill({ backend: 'tmux', paneId: '*' })).toMatchObject({ state: 'failed', dispatch: 'not_started' })
+ })
+
it('styles panes with the theme the app last sent, and re-styles existing ones on a scan', async () => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-theme-'))
dirs.push(dir)
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 4256da728..2f1f312e7 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -33,7 +33,7 @@ import {
setPaneWindowStyle,
} from './tmux.js'
import { DEFAULT_HOST_THEME, windowStyleOf, type HostTheme } from './hostTheme.js'
-import { listTmuxPanes } from './tmuxAgentDiscovery.js'
+import { isNoTmuxServerError, listTmuxPanes } from './tmuxAgentDiscovery.js'
import { terminalRouteKey } from './terminalRuntime.js'
const TMUX_KEYS: Record<TerminalLogicalKey, string> = {
@@ -190,12 +190,26 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
}
async kill(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {
- const sessionId = await this.resolveSessionId(runtime.paneId)
- if (!sessionId) return terminalActionNotStarted('tmux session could not be resolved from pane')
+ if (!/^%\d+$/.test(runtime.paneId)) return terminalActionNotStarted('invalid tmux pane identity')
+ // Discovered harnesses can share a tmux session with unrelated work. The
+ // canonical pane id is the entire target; never widen this to kill-session.
const ok = await new Promise<boolean>((resolve) => {
- execFile('tmux', ['kill-session', '-t', sessionId], { timeout: 5_000 }, (error) => resolve(!error))
+ execFile('tmux', ['kill-pane', '-t', runtime.paneId], { timeout: 5_000 }, (error) => resolve(!error))
+ })
+ if (ok) return TERMINAL_ACTION_SUCCEEDED
+ // The engine may have exited and removed its pane before the parallel PID
+ // check completed. Only authoritative inventory makes that an idempotent success.
+ // Use all panes here: discovery deliberately hides sessions that were renamed
+ // or created elsewhere, and their absence from discovery is not proof of exit.
+ const absent = await new Promise<boolean>(resolve => {
+ execFile('tmux', ['list-panes', '-a', '-F', '#{pane_id}'], { timeout: 2_000 }, (error, stdout) => {
+ if (error) { resolve(isNoTmuxServerError(error.message)); return }
+ const ids = stdout.trim().split('\n').filter(Boolean)
+ resolve(ids.every(id => /^%\d+$/.test(id)) && !ids.includes(runtime.paneId))
+ })
})
- return legacyActionResult(ok, 'tmux session close')
+ if (absent) return TERMINAL_ACTION_SUCCEEDED
+ return legacyActionResult(false, 'tmux pane close')
}
/**
diff --git a/desktop/README.md b/desktop/README.md
index 3e024b146..2048161ab 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -29,6 +29,39 @@ flutter build linux --release # must run on an Ubuntu host — no cross-compil
The terminal core is vendored at `third_party/xterm`. Do not replace it with an
upstream package upgrade without preserving the local rendering and IME fixes.
+## Harness manager
+
+The terminal icon to the left of Harness Store opens a compact list across your
+machines. Each harness shows its agent and name, followed by its machine, project,
+branch, and last activity (`5m`, `1h`, `2d`). Search matches names, machines,
+projects, branches, and pending questions. Filter All, Needs input, Running, or
+Paused; sort by recently active, name, machine, or project.
+
+Needs input replaces the separate bell. A red count badge at the terminal icon’s
+top-right corner appears only when harnesses need input. An amber help action
+opens the waiting harness; its question appears on a third line in the Needs input
+view. The same view opens with **⌘⇧I**. Questions update live and stale actions
+cannot redirect you after a question is answered or replaced elsewhere.
+
+Select a row to reveal its existing pane or resume and open saved work. The
+separate play button resumes in the background. Pause/play remains at the right;
+normal states need no redundant labels.
+
+Pause uses the CLI's existing stop operation, keeping the saved conversation and
+project on its machine. Pause/resume controls are enabled for saved Claude and
+Codex conversations; other engines remain openable with a tooltip explaining
+that exact resume is unavailable. The CLI confirms termination of the exact process
+and pane before publishing the paused state, preserving other panes in the same
+tmux session. A failed inventory refresh keeps confirmed paused work visible,
+and pending operations survive closing the manager.
+
+Closing a pane only hides its view: a curved Genie animation draws it into
+Harnesses while the process continues. A bounded GPU snapshot animates while the
+live terminal stays mounted at its original size. macOS Reduce Motion skips it.
+Offline and shared harnesses expose their state without offering process controls.
+Errors remain beside the affected row, and an uncertain resume checks its original
+receipt rather than starting the process twice.
+
## Open media from agent output
Hold **⌘ and click** on macOS, or **Ctrl and click** on Linux, to open an
diff --git a/desktop/integration_test/native_resume_e2e_test.dart b/desktop/integration_test/native_resume_e2e_test.dart
index c872536c6..bf3d33d41 100644
--- a/desktop/integration_test/native_resume_e2e_test.dart
+++ b/desktop/integration_test/native_resume_e2e_test.dart
@@ -4,6 +4,7 @@
import 'dart:convert';
import 'dart:io';
+import 'package:flutter/foundation.dart' show debugPrintSynchronously;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -11,6 +12,8 @@ import 'package:integration_test/integration_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/test_run.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/widgets/harness_session_manager.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -29,6 +32,9 @@ void main() {
testWidgets(
'real Claude/Codex stop, Cmd-P/T search, resume, registry and terminal history',
(tester) async {
+ final previousDebugPrint = debugPrint;
+ debugPrint = debugPrintSynchronously;
+ addTearDown(() => debugPrint = previousDebugPrint);
final http = HttpClient();
addTearDown(() => http.close(force: true));
Future<Map<String, dynamic>> get(String path) async {
@@ -41,17 +47,33 @@ void main() {
return body;
}
+ late AppNotifier app;
+ final events = <String>[];
Future<void> until(bool Function() condition, String label) async {
- final deadline = DateTime.now().add(const Duration(seconds: 60));
- while (!condition() && DateTime.now().isBefore(deadline)) {
+ final waiting = Stopwatch()..start();
+ while (!condition() && waiting.elapsed < const Duration(seconds: 60)) {
await tester.pump(const Duration(milliseconds: 100));
await Future<void>.delayed(const Duration(milliseconds: 100));
}
+ // Socket events can arrive during the real-time delay after a pump.
+ // Present their enabled controls before the next simulated click.
+ await tester.pump();
+ if (!condition()) {
+ debugPrint('Timed out waiting for $label after ${waiting.elapsed}');
+ debugPrint(events.join('\n'));
+ debugPrint(
+ 'Fixture agents: ${app.stateOf('m')?.agents.map((a) => (a.id, a.status, a.launchState, a.launchError))}',
+ );
+ for (final pane in app.allPanes) {
+ debugPrint(
+ 'Fixture pane ${pane.agentId}: ${pane.session?.status} ${pane.session?.errorMessage} stream=${pane.session?.streamId} ${pane.session?.terminal.buffer.getText()}',
+ );
+ }
+ }
expect(condition(), isTrue, reason: label);
}
final data = await get('/fixtures');
- late AppNotifier app;
final connection = WsConn(
wsBaseUrl: '',
autonomousEnv: 'test',
@@ -62,7 +84,18 @@ void main() {
),
accessTokenProvider: (_, _) async => '',
onAuthFailure: (_) {},
- onEvent: (frame) => app.handleEventForTest('m', frame),
+ onEvent: (frame) {
+ if (const [
+ 'agent_synced',
+ 'terminal_ready',
+ 'terminal_closed',
+ 'terminal_error',
+ ].contains(frame['type'])) {
+ events.add('Fixture event: ${jsonEncode(frame)}');
+ if (events.length > 40) events.removeAt(0);
+ }
+ return app.handleEventForTest('m', frame);
+ },
onStatus: (_) {},
);
app = createApp(connectionForTest: (_) => connection);
@@ -102,8 +135,15 @@ void main() {
final id = fixture['agentId'] as String;
final engine = fixture['engine'] as String;
final marker = fixture['marker'] as String;
+ debugPrint('Native manager verification: $engine');
Future<Map<String, dynamic>> open(LogicalKeyboardKey key) async {
+ // A network receipt can finish before the frame that moves keyboard
+ // focus away from the removed terminal.
+ await tester.pump();
await chord(tester, key);
+ if (key == LogicalKeyboardKey.keyT) {
+ await chord(tester, LogicalKeyboardKey.keyO);
+ }
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
@@ -157,9 +197,99 @@ void main() {
expect(attached['pid'], previous['pid']);
expect(attached['pane'], previous['pane']);
expect(await app.deleteAgent('m', id), isNull);
+
+ // Exercise the actual manager against native engine processes and disk
+ // history, including rapid double clicks and repeated background resume.
+ final toggle = find.byKey(
+ ValueKey('session-toggle:${agentDestinationId('m', id)}'),
+ );
+ for (var cycle = 0; cycle < 3; cycle++) {
+ debugPrint('Native manager $engine cycle ${cycle + 1}/3');
+ await until(
+ () =>
+ app.stateOf('m')!.agents.any((a) => a.id == id && a.isStopped),
+ '$engine saved row before manager cycle $cycle',
+ );
+ await tester.tap(find.byTooltip('Harnesses'));
+ await tester.pump();
+ await tester.tap(toggle);
+ await tester.tap(toggle);
+ await until(
+ () => app
+ .stateOf('m')!
+ .agents
+ .any(
+ (a) => a.id == id && !a.isStopped && a.launchState == 'ready',
+ ),
+ '$engine manager resume $cycle',
+ );
+ await until(
+ () => !app.restartAttempt('m', id).busy,
+ '$engine resume receipt $cycle',
+ );
+ expect(find.byType(HarnessSessionManager), findsOneWidget);
+ expect(
+ app.allPanes.any((p) => p.agentId == id),
+ isFalse,
+ reason: 'Play resumes in the background',
+ );
+ final resumed = await get('/verify?id=$id');
+ expect(resumed['sessionId'], fixture['sessionId']);
+ expect(resumed['pid'], isNot(previous['pid']));
+ previous = resumed;
+
+ expect(
+ tester
+ .widget<Semantics>(
+ find.byKey(
+ ValueKey('session-open:${agentDestinationId('m', id)}'),
+ ),
+ )
+ .properties
+ .enabled,
+ isTrue,
+ );
+ await tester.tap(
+ find.byKey(ValueKey('session-open:${agentDestinationId('m', id)}')),
+ );
+ await until(
+ () => app.allPanes.any(
+ (p) =>
+ p.agentId == id &&
+ (p.session?.terminal.buffer.getText().contains(marker) ??
+ false),
+ ),
+ '$engine manager restores original terminal history $cycle',
+ );
+ expect(app.allPanes.any((p) => p.agentId == anchorId), isTrue);
+ expect(find.byType(HarnessSessionManager), findsNothing);
+ await tester.tap(find.byTooltip('Harnesses'));
+ await tester.pump();
+ await tester.tap(toggle);
+ await tester.tap(toggle);
+ await until(
+ () =>
+ app
+ .stateOf('m')!
+ .agents
+ .any((a) => a.id == id && a.isStopped) &&
+ app.pendingAgentPause('m', id) == null,
+ '$engine manager pause $cycle',
+ );
+ expect((await get('/verify?id=$id'))['stopped'], true);
+ expect(app.allPanes.any((p) => p.agentId == id), isFalse);
+ expect(app.allPanes.any((p) => p.agentId == anchorId), isTrue);
+ expect(find.byType(HarnessSessionManager), findsOneWidget);
+ await tester.tap(find.byTooltip('Close harnesses'));
+ await tester.pump();
+ }
}
await tester.pumpWidget(const SizedBox());
},
timeout: const Timeout(Duration(minutes: 8)),
+ // Let macOS own accessibility activation, as it does in production. A test
+ // handle retained across app deactivation keeps Dart's tree alive after the
+ // native bridge is reset; its next partial update can be mistaken for a root.
+ semanticsEnabled: false,
);
}
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 372894ae5..7b2b047cc 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -238,6 +238,9 @@ class Agent {
final GridWebSearch? gridWebSearch;
final String? parentAgentId;
final AgentProject? project;
+
+ /// The CLI's transcript/hook activity time, not its registry refresh time.
+ final DateTime? lastActivityAt;
final String status;
final String launchState;
final String? launchError;
@@ -307,6 +310,7 @@ class Agent {
this.gridWebSearch,
this.parentAgentId,
this.project,
+ this.lastActivityAt,
this.status = 'active',
this.launchState = 'ready',
this.launchError,
@@ -328,6 +332,11 @@ class Agent {
bool get isStopped => status == 'stopped';
+ /// Exact saved-conversation resume is currently implemented for these engines.
+ bool get canResumeConversation =>
+ (engine == 'claude' || engine == 'codex') &&
+ sessionId?.isNotEmpty == true;
+
/// Explicit names win. An automatic CLI label gives way to its session title.
String get displayName => _automaticHarnessName.hasMatch(name)
? (title?.trim().isNotEmpty == true ? title!.trim() : kUntitledPane)
@@ -393,6 +402,9 @@ class Agent {
gridWebSearch: GridWebSearch.fromWire(grid?['webSearch']),
parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),
project: AgentProject.fromJson(j['project']),
+ lastActivityAt: j['updatedAt'] is String
+ ? DateTime.tryParse(j['updatedAt'] as String)
+ : null,
status: (j['status'] as String?) ?? 'active',
launchState: launchState,
launchError: launchState == 'failed' ? _safeLabel(launch['error']) : null,
@@ -420,37 +432,39 @@ class Agent {
);
}
- Agent copyWith({String? name}) => Agent(
- id: id,
- sessionId: sessionId,
- name: name ?? this.name,
- title: title,
- engine: engine,
- engineDisplayName: engineDisplayName,
- engineIconHint: engineIconHint,
- codexHome: codexHome,
- gridModel: gridModel,
- gridWebSearch: gridWebSearch,
- parentAgentId: parentAgentId,
- project: project,
- status: status,
- launchState: launchState,
- launchError: launchError,
- launchDetail: launchDetail,
- terminalAvailable: terminalAvailable,
- terminalUnavailableReason: terminalUnavailableReason,
- dsh: dsh,
- dshName: dshName,
- viewerUrl: viewerUrl,
- viewerError: viewerError,
- viewerName: viewerName,
- verdict: verdict,
- forkedFrom: forkedFrom,
- forkable: forkable,
- permissionMode: permissionMode,
- bypassPermission: bypassPermission,
- namedAgent: namedAgent,
- );
+ Agent copyWith({String? name, String? status, bool? terminalAvailable}) =>
+ Agent(
+ id: id,
+ sessionId: sessionId,
+ name: name ?? this.name,
+ title: title,
+ engine: engine,
+ engineDisplayName: engineDisplayName,
+ engineIconHint: engineIconHint,
+ codexHome: codexHome,
+ gridModel: gridModel,
+ gridWebSearch: gridWebSearch,
+ parentAgentId: parentAgentId,
+ project: project,
+ lastActivityAt: lastActivityAt,
+ status: status ?? this.status,
+ launchState: launchState,
+ launchError: launchError,
+ launchDetail: launchDetail,
+ terminalAvailable: terminalAvailable ?? this.terminalAvailable,
+ terminalUnavailableReason: terminalUnavailableReason,
+ dsh: dsh,
+ dshName: dshName,
+ viewerUrl: viewerUrl,
+ viewerError: viewerError,
+ viewerName: viewerName,
+ verdict: verdict,
+ forkedFrom: forkedFrom,
+ forkable: forkable,
+ permissionMode: permissionMode,
+ bypassPermission: bypassPermission,
+ namedAgent: namedAgent,
+ );
/// A mode id as `PERMISSION_MODES` spells them (`acceptEdits`, `readOnly`):
/// one word. Not checked against this build's own list — the daemon that
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 13baa75c3..955dae3b8 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -25,6 +25,7 @@ import '../shortcuts/keymap_host.dart';
import '../shortcuts/keymap_native.dart';
import '../shortcuts/keymap_settings.dart';
import '../state/app_state.dart';
+import '../state/harness_sessions.dart';
import '../state/harness_placement.dart';
import '../state/new_harness.dart';
import '../state/pane_arrangement.dart';
@@ -32,7 +33,6 @@ import '../terminal/terminal_viewport.dart';
import '../terminal/terminal_text.dart';
import '../usage/models_menu_controller.dart';
import '../state/swarm_catalog.dart';
-import '../state/swarm_attention.dart';
import '../state/swarm_navigation.dart';
import '../state/swarm_search.dart';
import '../state/swarm.dart';
@@ -55,13 +55,14 @@ import '../widgets/box_chrome.dart';
import '../widgets/new_harness_box.dart';
import '../widgets/open_harness_intent.dart';
import '../widgets/pane_grid.dart';
+import '../widgets/pane_minimize.dart';
+import '../widgets/harness_session_manager.dart';
import '../widgets/remote_folder_picker.dart';
import '../widgets/shortcuts_sheet.dart';
import '../widgets/harness_customize_pane.dart';
import '../shared/widgets/app_dialog.dart';
import '../widgets/swarm_dialogs.dart';
import '../widgets/swarm_search_input.dart';
-import '../widgets/swarm_attention.dart';
import '../widgets/swarm_switcher.dart';
import '../widgets/swarm_wallpaper.dart';
import '../widgets/swarm_icon.dart';
@@ -121,7 +122,8 @@ typedef _NewHarnessContext = ({
TextStyle get _boxCaption =>
grid.AppType.monoLabel(color: kBoxFaint, fontWeight: FontWeight.w400);
-class _SwarmScreenState extends State<SwarmScreen> {
+class _SwarmScreenState extends State<SwarmScreen>
+ with SingleTickerProviderStateMixin {
static const _channel = MethodChannel('harness/swarm_tabs');
late final bool _native =
widget.nativeTabs ?? (Platform.isMacOS && !kUnderTest);
@@ -130,6 +132,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
SwarmProjectStore(storage: kUnderTest ? null : HarnessFileStore.shared);
StreamSubscription<SpokenTaskRequest>? _spokenTasks;
final _shellFocus = FocusNode(debugLabel: 'Swarm shell');
+ final _sessionsButton = GlobalKey();
+ OverlayEntry? _sessionsOverlay;
+ VoidCallback? _unregisterSessions;
+ late final _minimize = PaneMinimizeController(vsync: this);
+ bool _closingPane = false;
+ OverlayEntry? _minimizeOverlay;
final _startSearchFocus = FocusNode(debugLabel: 'Start page search');
final _commandFocus = FocusNode(debugLabel: 'Ask Harness');
bool _commandBarOpen = false;
@@ -257,11 +265,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
final current = ModalRoute.isCurrentOf(context) ?? true;
if (_routeIsCurrent == current) return;
_routeIsCurrent = current;
- if (!current && (_search != null || _commandBarOpen)) {
+ if (!current &&
+ (_search != null || _commandBarOpen || _sessionsOverlay != null)) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && !_routeIsCurrent) {
_closeSearch(restoreFocus: false);
_closeCommandBar(restoreFocus: false);
+ _closeSessions(restoreFocus: false);
}
});
}
@@ -270,6 +280,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
@override
void dispose() {
+ _unregisterSessions?.call();
+ _sessionsOverlay?.remove();
+ _sessionsOverlay?.dispose();
+ _minimizeOverlay?.remove();
+ _minimizeOverlay?.dispose();
+ _minimizeOverlay = null;
+ _minimize.dispose();
_keymap.removeListener(_keymapChanged);
_defaultKeymap.dispose();
grid.AppTheme.palette.removeListener(_paletteChanged);
@@ -357,6 +374,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
mounted && _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen;
void _runShortcut(String id) {
+ if (_sessionsOverlay != null) _closeSessions();
if (id != 'navigation.command_bar') _closeCommandBar();
if (id == 'agent.new' && _search != null) {
final target = _search!.targetId;
@@ -478,7 +496,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_dialog(() => showKeyboardPractice(context, keymap: _keymap));
int get _attention =>
- app.machineStates.values.fold(0, (n, m) => n + m.blockedAgents.length);
+ harnessSessions(app).where((row) => row.needsInput).length;
void _restoreEmptyFocus() {
if (!mounted ||
@@ -574,6 +592,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
},
],
'attention': _attention,
+ 'sessionsOpen': _sessionsOverlay != null,
+ 'runningSessions': harnessSessions(app)
+ .where((row) => row.running)
+ .length,
'history': [
for (final entry in _navigation.menuDestinations(app))
{
@@ -834,6 +856,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
final args = call.arguments is Map ? call.arguments as Map : const {};
+ if (call.method == 'sessions') {
+ _toggleSessions();
+ await WidgetsBinding.instance.endOfFrame;
+ return;
+ }
if (call.method == 'modelsOpened') {
await _modelsMenu?.refresh();
return;
@@ -1056,7 +1083,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
case 'closePane':
- if (app.focusedPaneId != null) await app.closePane(app.focusedPaneId!);
+ if (app.focusedPane case final pane?) unawaited(_closePane(pane));
case 'findTerminal':
app.focusedPane?.session?.find(TerminalFindAction.open);
case 'findNext':
@@ -1889,6 +1916,168 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.openStore();
}
+ void _toggleSessions({SessionFilter? filter}) {
+ if (_sessionsOverlay != null) {
+ _closeSessions(restoreFocus: filter == null);
+ if (filter == null) return;
+ }
+ if (_newHarness?.requestDismiss() == false) return;
+ _closeNewHarness(restoreFocus: false);
+ _closeSearch(restoreFocus: false);
+ _closeCommandBar(restoreFocus: false);
+ dismissTransientMenus();
+ _preparePaneFocus();
+ final overlay = Overlay.of(context);
+ _sessionsOverlay = OverlayEntry(
+ builder: (context) => LayoutBuilder(
+ builder: (context, constraints) => Stack(
+ children: [
+ Positioned.fill(
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: _closeSessions,
+ child: const SizedBox.expand(),
+ ),
+ ),
+ Positioned(
+ top: (_native ? 0.0 : _tabBarHeight) + 8,
+ right: 10,
+ width: (constraints.maxWidth - 20).clamp(0, 640),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight:
+ (constraints.maxHeight -
+ (_native ? 0 : _tabBarHeight) -
+ 20)
+ .clamp(0, 620),
+ ),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(14),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black.withValues(alpha: .35),
+ blurRadius: 36,
+ offset: const Offset(0, 12),
+ ),
+ ],
+ border: Border.all(
+ color: grid.AppPalette.textPrimary.withValues(alpha: .12),
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(1),
+ child: HarnessSessionManager(
+ app: app,
+ initialFilter: filter ?? SessionFilter.all,
+ recent: _navigation.recent,
+ onClose: _closeSessions,
+ onOpen: (row) async {
+ final destination = swarmDestinations(app)
+ .where((item) => item.id == row.id)
+ .firstOrNull;
+ if (destination == null) return false;
+ final opened = await activateSwarmDestination(
+ app,
+ destination,
+ destinationSwarmId: app.activeSwarmId,
+ );
+ return opened;
+ },
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ overlay.insert(_sessionsOverlay!);
+ _unregisterSessions = registerTransientMenu(_closeSessions);
+ if (_native) _syncNative();
+ setState(() {});
+ }
+
+ void _closeSessions({bool restoreFocus = true}) {
+ if (_sessionsOverlay == null) return;
+ _unregisterSessions?.call();
+ _unregisterSessions = null;
+ _sessionsOverlay?.remove();
+ _sessionsOverlay?.dispose();
+ _sessionsOverlay = null;
+ if (!mounted) return;
+ if (_native) _syncNative();
+ setState(() {});
+ if (restoreFocus) {
+ _shellFocus.requestFocus();
+ final pane = app.focusedPane;
+ if (pane != null) app.focusPane(pane.id, reveal: true);
+ }
+ }
+
+ Future<void> _closePane(TerminalPane pane) async {
+ if (_closingPane ||
+ pane.isWeb ||
+ pane.agentId == null ||
+ MediaQuery.disableAnimationsOf(context) ||
+ !_minimize.capture(pane)) {
+ await app.closePane(pane.id);
+ return;
+ }
+ _closingPane = true;
+ final tab = app.activeSwarmId;
+ final overlay = Overlay.of(context);
+ final box = overlay.context.findRenderObject() as RenderBox;
+ final origin = box.localToGlobal(Offset.zero);
+ _minimizeOverlay = OverlayEntry(
+ builder: (_) => Positioned.fromRect(
+ rect: _minimize.source.shift(-origin),
+ child: PaneMinimizeSnapshot(controller: _minimize),
+ ),
+ );
+ overlay.insert(_minimizeOverlay!);
+ // Close logically before the first await: the next keystroke belongs to
+ // the remaining pane, even while the captured pixels are still moving.
+ final closed = app.closePane(pane.id);
+ try {
+ Offset? target;
+ if (_native) {
+ final anchor = await _channel.invokeMapMethod<String, dynamic>(
+ 'sessionsAnchor',
+ );
+ if (anchor?['reduceMotion'] == true) return;
+ if (anchor?['x'] is num && anchor?['y'] is num) {
+ target = Offset(
+ (anchor!['x'] as num).toDouble(),
+ (anchor['y'] as num).toDouble(),
+ );
+ }
+ } else {
+ final button = _sessionsButton.currentContext?.findRenderObject();
+ if (button is RenderBox && button.hasSize) {
+ target = button.localToGlobal(button.size.center(Offset.zero));
+ }
+ }
+ if (!mounted || app.activeSwarmId != tab) return;
+ if (target != null) await _minimize.animate(target);
+ if (_native && mounted && app.activeSwarmId == tab) {
+ unawaited(_channel.invokeMethod<void>('sessionMinimized'));
+ }
+ } on TickerCanceled {
+ // Disposing the window cancels motion, never the agent process.
+ } on MissingPluginException {
+ // The pane is already closed; only the optional animation is skipped.
+ } finally {
+ _closingPane = false;
+ _minimizeOverlay?.remove();
+ _minimizeOverlay?.dispose();
+ _minimizeOverlay = null;
+ if (mounted) _minimize.reset();
+ await closed;
+ }
+ }
+
void _openSearch({
bool adding = false,
PaneSplitRequest? split,
@@ -2270,14 +2459,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (project != null) await _projects.add(project);
});
Future<void> _notifications() async {
- final target = app.activeSwarmId;
- SwarmAttentionEntry? selected;
- await _dialog(() async {
- selected = await showSwarmAttention(context, app, _navigation);
- });
- if (!mounted || selected == null) return;
- _preparePaneFocus();
- await activateSwarmAttention(app, selected!, destinationSwarmId: target);
+ _toggleSessions(filter: SessionFilter.needsInput);
}
Future<void> _openSpokenTask(SpokenTaskRequest request) async {
@@ -2368,8 +2550,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
ShortcutAction.showAttention: _notifications,
ShortcutAction.addAgent: _addAgent,
ShortcutAction.closePane: () {
- if (app.focusedPaneId != null) {
- app.closePane(app.focusedPaneId!);
+ if (app.focusedPane case final pane?) {
+ unawaited(_closePane(pane));
}
},
ShortcutAction.newAgent: _newAgent,
@@ -2723,7 +2905,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
@override
- Widget build(BuildContext context) => ListenableBuilder(
+ Widget build(BuildContext context) => PaneMinimizeScope(
+ controller: _minimize,
+ close: _closePane,
+ child: _buildWorkspace(context),
+ );
+
+ Widget _buildWorkspace(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([app, _projects, _learning]),
builder: (context, _) {
grid.AppTheme.watch(context);
@@ -3071,21 +3259,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
color: grid.AppPalette.swarmTabBar,
child: Row(
children: [
- IconButton(
- key: const ValueKey('swarm-notifications-button'),
- onPressed: _notifications,
- icon: Badge(
- isLabelVisible: _attention > 0,
- child: Icon(
- Icons.notifications_none,
- size: 20,
- semanticLabel: _attention > 0
- ? '$_attention agents need input'
- : 'Notifications',
- ),
- ),
- ),
- const SizedBox(width: 10),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
@@ -3217,6 +3390,34 @@ class _SwarmScreenState extends State<SwarmScreen> {
tooltip: 'New Tab ${_keymap.hint('swarm.new') ?? ''}'.trim(),
icon: const Icon(Icons.add, size: 18, semanticLabel: 'New Tab'),
),
+ IconButton(
+ key: _sessionsButton,
+ tooltip: 'Harnesses',
+ onPressed: _toggleSessions,
+ isSelected: _sessionsOverlay != null,
+ icon: Badge(
+ isLabelVisible: _attention > 0,
+ backgroundColor: const Color(0xffcf4038),
+ textColor: Colors.white,
+ largeSize: 13,
+ alignment: Alignment.topRight,
+ label: Text(
+ _attention > 99 ? '99+' : '$_attention',
+ semanticsLabel:
+ '$_attention ${_attention == 1 ? 'harness needs' : 'harnesses need'} input',
+ style: const TextStyle(
+ fontSize: 9,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ child: const Icon(
+ Icons.terminal_rounded,
+ size: 20,
+ semanticLabel: 'Harnesses',
+ ),
+ ),
+ ),
+ const SizedBox(width: 6),
Tooltip(
message: 'Harness Store ${_keymap.hint('app.store') ?? ''}'
.trim(),
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index fa25d234b..fd8e51d12 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -138,7 +138,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'navigation.needs_input',
- 'Show agents needing input',
+ 'Show harnesses needing input',
ShortcutGroup.navigate,
action: ShortcutAction.showAttention,
nativeAction: 'notifications',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 1e6a30ba0..94163b5d3 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -441,6 +441,7 @@ class AppNotifier extends ChangeNotifier {
final _machineEdits = <String, _MachineEdit>{};
final _agentRenames = <(String, String), _AgentRename>{};
final _agentStops = <(String, String), _AgentStop>{};
+ final _agentPauses = <(String, String), Future<String?>>{};
final _agentForks = <(String, String), AgentForkAttempt>{};
final _agentRestarts = <(String, String), AgentRestartAttempt>{};
int _machineEditRevision = 0;
@@ -608,6 +609,7 @@ class AppNotifier extends ChangeNotifier {
_machineEdits.clear();
_agentRenames.clear();
_agentStops.clear();
+ _agentPauses.clear();
_agentForks.clear();
_agentRestarts.clear();
_confirmedMachineEdits.clear();
@@ -4071,6 +4073,7 @@ class AppNotifier extends ChangeNotifier {
prev.codexHome != agent.codexHome ||
prev.parentAgentId != agent.parentAgentId ||
prev.project != agent.project ||
+ prev.lastActivityAt != agent.lastActivityAt ||
prev.launchState != agent.launchState ||
prev.launchError != agent.launchError ||
prev.launchDetail != agent.launchDetail ||
@@ -6891,6 +6894,51 @@ class AppNotifier extends ChangeNotifier {
: null;
}
+ Future<String?>? pendingAgentPause(String machineId, String agentId) =>
+ _agentPauses[(machineId, agentId)];
+
+ /// Keep confirmed paused work visible even if its subsequent inventory refresh
+ /// fails or the manager is dismissed. The daemon remains the durable authority.
+ Future<String?> pauseAgent(String machineId, String agentId) {
+ final key = (machineId, agentId);
+ if (_agentPauses[key] case final pending?) return pending;
+ final machine = stateOf(machineId);
+ final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
+ if (machine == null || agent == null || !agent.canResumeConversation) {
+ return Future.value(
+ 'This harness has no supported saved conversation to resume.',
+ );
+ }
+ if (agent.isStopped) return Future.value(null);
+ final revision = _authRevision;
+ late final Future<String?> pause;
+ pause = (() async {
+ final error = await deleteAgent(machineId, agentId);
+ if (!_machineWorkCurrent(machine, revision)) return error;
+ final current = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ if (error == null && current == null) {
+ _upsertAgent(
+ machine,
+ agent.copyWith(status: 'stopped', terminalAvailable: false),
+ );
+ notifyListeners();
+ }
+ await reloadMachineData(machineId);
+ if (!_machineWorkCurrent(machine, revision)) return error;
+ final observed = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ // A lost reply is resolved by authoritative inventory, never by resending Stop.
+ if (observed?.isStopped == true && observed?.sessionId == agent.sessionId) {
+ return null;
+ }
+ return error;
+ })().whenComplete(() {
+ if (identical(_agentPauses[key], pause)) _agentPauses.remove(key);
+ if (_authWorkCurrent(revision)) notifyListeners();
+ });
+ _agentPauses[key] = pause;
+ return pause;
+ }
+
/// Stops the process through the CLI, retaining project files and history.
/// The request outlives its confirmation and is shared by every view.
///
@@ -6972,12 +7020,20 @@ class AppNotifier extends ChangeNotifier {
'Stop failed: ${detail is String && detail.isNotEmpty ? detail : code}';
return;
}
+ if (result['deleted'] != true) {
+ error = 'Could not confirm the pause. Refresh to check its status.';
+ return;
+ }
await _removeAgent(request.machine, agentId);
} catch (failure) {
if (!request.confirmed) {
- error = failure is WsRequestTimeout
- ? 'Could not confirm the stop. Refresh agents to check its status.'
- : 'Could not stop the agent. Try again.';
+ error = switch (failure) {
+ WsRequestFailure(:final code, :final detail) =>
+ 'Stop failed: ${detail != null && detail.isNotEmpty ? detail : code}',
+ WsRequestTimeout() =>
+ 'Could not confirm the stop. Refresh agents to check its status.',
+ _ => 'Could not stop the agent. Try again.',
+ };
}
} finally {
if (identical(_agentStops[(machineId, agentId)], request)) {
@@ -7037,6 +7093,11 @@ class AppNotifier extends ChangeNotifier {
/// Attach to a running harness or resume its saved conversation immediately.
Future<RestartAgentResult> resumeAgent(String machineId, String agentId) {
+ if (pendingAgentPause(machineId, agentId) != null) {
+ return Future.value(const RestartAgentResult(
+ error: 'The harness is still pausing. Try again in a moment.',
+ ));
+ }
final agent = stateOf(machineId)?.agents
.where((agent) => agent.id == agentId)
.firstOrNull;
diff --git a/desktop/lib/state/harness_sessions.dart b/desktop/lib/state/harness_sessions.dart
new file mode 100644
index 000000000..6aaf5779a
--- /dev/null
+++ b/desktop/lib/state/harness_sessions.dart
@@ -0,0 +1,196 @@
+import 'package:collection/collection.dart' show compareNatural;
+
+import '../core/models.dart';
+import 'app_state.dart';
+import 'pending_question.dart';
+import 'swarm_navigation.dart';
+
+enum SessionFilter { all, needsInput, running, paused }
+
+enum SessionSort {
+ recent('Recently active'),
+ name('Name'),
+ machine('Machine'),
+ project('Project');
+
+ const SessionSort(this.label);
+ final String label;
+}
+
+/// A session appears once, however many tabs or viewers show it.
+class HarnessSession {
+ const HarnessSession({
+ required this.machine,
+ required this.agent,
+ required this.open,
+ required this.working,
+ this.question,
+ });
+
+ final MachineState machine;
+ final Agent agent;
+ final bool open, working;
+ final PendingQuestion? question;
+ bool get needsInput => question != null && !agent.isStopped;
+ DateTime? get lastActiveAt => agent.lastActivityAt;
+ String get machineId => machine.machine.machineId;
+ String get id => agentDestinationId(machineId, agent.id);
+ AgentProject? get project => machine.projectOf(agent);
+ bool get online =>
+ machine.nodeOnline != false &&
+ !machine.needsLink &&
+ (machine.machine.isShared ||
+ machine.connectionStatus == ConnectionStatus.connected) &&
+ (!machine.isLocalMachine || machine.usesLocalTransport);
+ bool get running => online && !agent.isStopped && agent.terminalAvailable;
+ bool get canOpen =>
+ open ||
+ (online &&
+ (agent.terminalAvailable ||
+ (agent.isStopped &&
+ agent.canResumeConversation &&
+ !machine.machine.isShared)));
+ bool get canControl =>
+ online &&
+ !machine.machine.isShared &&
+ agent.canResumeConversation &&
+ (agent.isStopped || agent.terminalAvailable) &&
+ agent.launchState != 'starting';
+ String get status => !online
+ ? 'Offline'
+ : machine.machine.isShared
+ ? 'View only'
+ : agent.isStopped
+ ? (agent.canResumeConversation ? 'Paused' : 'Resume unavailable')
+ : agent.launchState == 'failed'
+ ? 'Start failed'
+ : agent.launchState == 'starting'
+ ? 'Starting'
+ : needsInput
+ ? 'Needs input'
+ : working
+ ? 'Working'
+ : agent.terminalAvailable
+ ? 'Ready'
+ : 'Unavailable';
+ String? get controlUnavailable => !online
+ ? 'Reconnect ${machine.machine.displayName} to control this harness.'
+ : machine.machine.isShared
+ ? 'Shared harnesses are view-only.'
+ : !agent.canResumeConversation
+ ? (agent.engine == 'claude' || agent.engine == 'codex'
+ ? 'Waiting for a saved conversation before enabling pause and resume.'
+ : 'Pause and resume are not available for this engine yet.')
+ : !canControl
+ ? agent.launchDetail ??
+ agent.terminalUnavailableReason ??
+ 'This harness is not ready yet.'
+ : null;
+}
+
+List<HarnessSession> harnessSessions(AppNotifier app) {
+ final open = {
+ for (final pane in app.allPanes)
+ if (pane.agentId != null) (pane.machineId, pane.agentId),
+ };
+ return [
+ for (final machine in app.machineStates.values)
+ for (final agent in machine.agents)
+ HarnessSession(
+ machine: machine,
+ agent: agent,
+ open: open.contains((machine.machine.machineId, agent.id)),
+ working: machine.processingAgentIds.contains(agent.id),
+ question: machine.blockedAgents[agent.id],
+ ),
+ // Keep a real pending question visible while its roster entry is missing.
+ // It must never become an invented terminal or a target for Pause.
+ for (final machine in app.machineStates.values)
+ for (final question in machine.blockedAgents.values)
+ if (!machine.agents.any((agent) => agent.id == question.agentId))
+ HarnessSession(
+ machine: machine,
+ agent: Agent(id: question.agentId, name: 'Unavailable harness'),
+ open: open.contains((machine.machine.machineId, question.agentId)),
+ working: false,
+ question: question,
+ ),
+ ];
+}
+
+List<HarnessSession> visibleHarnessSessions(
+ List<HarnessSession> sessions, {
+ String query = '',
+ SessionFilter filter = SessionFilter.all,
+ SessionSort sort = SessionSort.recent,
+ List<String> recent = const [],
+}) {
+ final terms = query.toLowerCase().trim().split(RegExp(r'\s+'));
+ final result = sessions.where((row) {
+ if (filter == SessionFilter.running && !row.running) return false;
+ if (filter == SessionFilter.needsInput && !row.needsInput) return false;
+ if (filter == SessionFilter.paused && !row.agent.isStopped) return false;
+ final text = [
+ row.agent.displayName,
+ row.agent.name,
+ row.agent.title,
+ row.agent.identityEngine,
+ row.machine.machine.displayName,
+ row.project?.name,
+ row.project?.label,
+ row.project?.cwd,
+ row.project?.branch,
+ row.status,
+ row.question?.prompt,
+ ].whereType<String>().join(' ').toLowerCase();
+ return terms.every(text.contains);
+ }).toList();
+ final ranks = {for (var i = 0; i < recent.length; i++) recent[i]: i};
+ result.sort((a, b) {
+ final comparison = switch (sort) {
+ SessionSort.recent => _byActivity(a, b, ranks, recent.length),
+ SessionSort.name => compareNatural(
+ a.agent.displayName.toLowerCase(),
+ b.agent.displayName.toLowerCase(),
+ ),
+ SessionSort.machine => compareNatural(
+ a.machine.machine.displayName.toLowerCase(),
+ b.machine.machine.displayName.toLowerCase(),
+ ),
+ SessionSort.project => compareNatural(
+ (a.project?.label ?? '').toLowerCase(),
+ (b.project?.label ?? '').toLowerCase(),
+ ),
+ };
+ if (comparison != 0) return comparison;
+ final name = compareNatural(
+ a.agent.displayName.toLowerCase(),
+ b.agent.displayName.toLowerCase(),
+ );
+ return name == 0 ? a.id.compareTo(b.id) : name;
+ });
+ return result;
+}
+
+int _byActivity(
+ HarnessSession a,
+ HarnessSession b,
+ Map<String, int> ranks,
+ int fallback,
+) {
+ final activity = (b.lastActiveAt?.millisecondsSinceEpoch ?? 0).compareTo(
+ a.lastActiveAt?.millisecondsSinceEpoch ?? 0,
+ );
+ return activity != 0
+ ? activity
+ : (ranks[a.id] ?? fallback).compareTo(ranks[b.id] ?? fallback);
+}
+
+/// Compact elapsed activity, including old-daemon and clock-skew fallbacks.
+String harnessActivityAge(DateTime? activity, DateTime now) {
+ if (activity == null) return '—';
+ final elapsed = now.difference(activity);
+ if (elapsed.inDays >= 1) return '${elapsed.inDays}d';
+ if (elapsed.inHours >= 1) return '${elapsed.inHours}h';
+ return '${elapsed.inMinutes.clamp(0, 59)}m';
+}
diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dart
new file mode 100644
index 000000000..051da90d6
--- /dev/null
+++ b/desktop/lib/widgets/harness_session_manager.dart
@@ -0,0 +1,827 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import '../shared/theme/app_theme.dart';
+import '../shared/widgets/app_menu.dart';
+import '../state/app_state.dart';
+import '../state/harness_sessions.dart';
+import '../state/swarm_navigation.dart';
+import 'engine_identity.dart';
+
+/// A compact, live inventory. Action receipts belong to AppNotifier, so
+/// dismissing this surface never cancels a pause or launches a second resume.
+class HarnessSessionManager extends StatefulWidget {
+ const HarnessSessionManager({
+ super.key,
+ required this.app,
+ required this.recent,
+ required this.onClose,
+ required this.onOpen,
+ this.initialFilter = SessionFilter.all,
+ });
+ final AppNotifier app;
+ final List<String> recent;
+ final VoidCallback onClose;
+ final Future<bool> Function(HarnessSession) onOpen;
+ final SessionFilter initialFilter;
+
+ @override
+ State<HarnessSessionManager> createState() => _HarnessSessionManagerState();
+}
+
+class _HarnessSessionManagerState extends State<HarnessSessionManager> {
+ final _search = TextEditingController();
+ final _searchFocus = FocusNode(debugLabel: 'Search harnesses');
+ final _scroll = ScrollController();
+ final _sortMenu = MenuController();
+ final _pending = <String, HarnessSession>{};
+ final _errors = <String, String>{};
+ late SessionFilter _filter;
+ Timer? _clock;
+ SessionSort _sort = SessionSort.recent;
+ String? _selected;
+ int _selectedIndex = 0;
+ final _rowKeys = <String, GlobalKey>{};
+ String? _opening;
+
+ @override
+ void initState() {
+ super.initState();
+ _filter = widget.initialFilter;
+ _clock = Timer.periodic(const Duration(minutes: 1), (_) => _changed());
+ widget.app.addListener(_changed);
+ }
+
+ void _changed() {
+ if (mounted) setState(() {});
+ }
+
+ @override
+ void dispose() {
+ widget.app.removeListener(_changed);
+ _clock?.cancel();
+ _search.dispose();
+ _searchFocus.dispose();
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ List<HarnessSession> get _sessions {
+ final rows = {for (final row in harnessSessions(widget.app)) row.id: row};
+ // Keep the row steady while a confirmed pause refreshes the saved roster.
+ for (final row in _pending.values) {
+ rows.putIfAbsent(row.id, () => row);
+ }
+ return rows.values.toList();
+ }
+
+ Future<void> _toggle(HarnessSession row) async {
+ if (_pending.containsKey(row.id) || !row.canControl) return;
+ final current = widget.app
+ .stateOf(row.machineId)
+ ?.agents
+ .where((agent) => agent.id == row.agent.id)
+ .firstOrNull;
+ if (!identical(widget.app.stateOf(row.machineId), row.machine) ||
+ current == null ||
+ current.sessionId != row.agent.sessionId ||
+ current.isStopped != row.agent.isStopped) {
+ return;
+ }
+ setState(() {
+ _pending[row.id] = row;
+ _errors.remove(row.id);
+ });
+ String? error;
+ try {
+ if (row.agent.isStopped) {
+ error = (await widget.app.resumeAgent(
+ row.machineId,
+ row.agent.id,
+ )).error;
+ } else {
+ error = await widget.app.pauseAgent(row.machineId, row.agent.id);
+ }
+ } catch (_) {
+ error =
+ 'Could not ${row.agent.isStopped ? 'resume' : 'pause'} this harness. Try again.';
+ }
+ if (!mounted) return;
+ setState(() {
+ _pending.remove(row.id);
+ if (error != null) {
+ _errors[row.id] = error.replaceFirst('Stop failed:', 'Pause failed:');
+ }
+ });
+ }
+
+ Future<void> _open(HarnessSession row, {bool answering = false}) async {
+ if (answering) {
+ final current = widget.app.questionFor(row.machineId, row.agent.id);
+ if (current == null || row.question?.sameAs(current) != true) return;
+ }
+ final awaitingInput =
+ row.agent.terminalAvailable && row.agent.launchState == 'starting';
+ if (_opening != null ||
+ (_pending.containsKey(row.id) && !awaitingInput) ||
+ !row.canOpen) {
+ return;
+ }
+ setState(() {
+ _opening = row.id;
+ _errors.remove(row.id);
+ });
+ try {
+ final opened = await widget.onOpen(row);
+ if (mounted && opened) widget.onClose();
+ } on SwarmResumeFailure catch (failure) {
+ if (mounted) setState(() => _errors[row.id] = failure.message);
+ } catch (_) {
+ if (mounted) {
+ setState(
+ () => _errors[row.id] = 'Could not open this harness. Try again.',
+ );
+ }
+ } finally {
+ if (mounted) setState(() => _opening = null);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final all = _sessions;
+ final rows = visibleHarnessSessions(
+ all,
+ query: _search.text,
+ filter: _filter,
+ sort: _sort,
+ recent: widget.recent,
+ );
+ final running = all.where((row) => row.running).length;
+ final paused = all.where((row) => row.agent.isStopped).length;
+ final needsInput = all.where((row) => row.needsInput).length;
+ final now = DateTime.now();
+ final showingQuestions = _filter == SessionFilter.needsInput;
+ final selected =
+ rows.where((row) => row.id == _selected).firstOrNull ??
+ (rows.isEmpty
+ ? null
+ : rows[_selected == null
+ ? 0
+ : _selectedIndex.clamp(0, rows.length - 1)]);
+ if (_selected != null && selected != null) {
+ _selected = selected.id;
+ _selectedIndex = rows.indexOf(selected);
+ }
+ final scale = MediaQuery.textScalerOf(context);
+ final rowHeight =
+ math.max(
+ 62.0,
+ scale.scale(AppType.bodySize) * 1.4 +
+ scale.scale(AppType.monoMetaSize) * 1.4 +
+ 26,
+ ) +
+ (showingQuestions ? scale.scale(AppType.monoMetaSize) * 1.4 + 6 : 0);
+ return FocusScope(
+ child: CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.escape): widget.onClose,
+ },
+ child: Focus(
+ onKeyEvent: (_, event) {
+ if (event is! KeyDownEvent ||
+ rows.isEmpty ||
+ !_searchFocus.hasFocus) {
+ return KeyEventResult.ignored;
+ }
+ final key = event.logicalKey;
+ if ((key == LogicalKeyboardKey.enter ||
+ key == LogicalKeyboardKey.numpadEnter) &&
+ _search.value.composing.isCollapsed) {
+ final row = selected!;
+ unawaited(_open(row, answering: row.needsInput));
+ return KeyEventResult.handled;
+ }
+ if (key != LogicalKeyboardKey.arrowDown &&
+ key != LogicalKeyboardKey.arrowUp) {
+ return KeyEventResult.ignored;
+ }
+ final at = rows.indexOf(selected!);
+ final next = _selected == null
+ ? (key == LogicalKeyboardKey.arrowDown ? 0 : rows.length - 1)
+ : (at + (key == LogicalKeyboardKey.arrowDown ? 1 : -1)).clamp(
+ 0,
+ rows.length - 1,
+ );
+ setState(() => _selected = rows[next].id);
+ void reveal() {
+ final context = _rowKeys[rows[next].id]?.currentContext;
+ if (!mounted || context == null) return;
+ Scrollable.ensureVisible(
+ context,
+ alignmentPolicy: key == LogicalKeyboardKey.arrowDown
+ ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd
+ : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
+ );
+ }
+
+ if (_rowKeys[rows[next].id]?.currentContext != null) {
+ reveal();
+ } else if (_scroll.hasClients) {
+ // Materialize a distant row, then use its real bounds. Question
+ // text, errors, row padding and enlarged type all affect height.
+ _scroll.jumpTo(
+ (6 + next * (rowHeight + 2)).clamp(
+ 0,
+ _scroll.position.maxScrollExtent,
+ ),
+ );
+ WidgetsBinding.instance.addPostFrameCallback((_) => reveal());
+ }
+ return KeyEventResult.handled;
+ },
+ child: Material(
+ key: const ValueKey('session-manager'),
+ color: AppPalette.panelBg,
+ borderRadius: BorderRadius.circular(14),
+ clipBehavior: Clip.antiAlias,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 10, 12, 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text('Harnesses', style: AppType.heading()),
+ ),
+ IconButton(
+ tooltip: 'Close harnesses',
+ onPressed: widget.onClose,
+ icon: const Icon(LucideIcons.x, size: 16),
+ ),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: TextField(
+ key: const ValueKey('session-search'),
+ controller: _search,
+ focusNode: _searchFocus,
+ autofocus: true,
+ style: AppType.monoLabel(),
+ onChanged: (_) => setState(() => _selected = null),
+ onSubmitted: (_) {
+ if (selected != null) unawaited(_open(selected));
+ },
+ decoration: InputDecoration(
+ hintText:
+ 'Search harnesses, machines, projects, branches…',
+ hintStyle: AppType.monoLabel(color: AppPalette.textFaint),
+ prefixIcon: Icon(
+ LucideIcons.search,
+ size: 15,
+ color: AppPalette.textFaint,
+ ),
+ prefixIconConstraints: const BoxConstraints(minWidth: 36),
+ suffixIcon: _search.text.isEmpty
+ ? null
+ : IconButton(
+ tooltip: 'Clear search',
+ icon: const Icon(LucideIcons.x, size: 14),
+ onPressed: () {
+ _search.clear();
+ setState(() => _selected = null);
+ _searchFocus.requestFocus();
+ },
+ ),
+ isDense: true,
+ filled: true,
+ fillColor: AppPalette.windowBg,
+ contentPadding: const EdgeInsets.symmetric(
+ vertical: 12,
+ horizontal: 12,
+ ),
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(8),
+ borderSide: BorderSide.none,
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(8),
+ borderSide: BorderSide(
+ color: AppPalette.accent.withValues(alpha: .8),
+ ),
+ ),
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 10, 12, 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ child: Row(
+ children: [
+ for (final filter in SessionFilter.values)
+ Padding(
+ padding: const EdgeInsets.only(right: 4),
+ child: Semantics(
+ selected: _filter == filter,
+ child: TextButton(
+ key: ValueKey(
+ 'session-filter:${filter.name}',
+ ),
+ onPressed: () => setState(() {
+ _filter = filter;
+ _selected = null;
+ }),
+ style: TextButton.styleFrom(
+ backgroundColor: _filter == filter
+ ? AppPalette.textPrimary.withValues(
+ alpha: .08,
+ )
+ : Colors.transparent,
+ foregroundColor: _filter == filter
+ ? AppPalette.textPrimary
+ : AppPalette.textSecondary,
+ minimumSize: const Size(0, 30),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ ),
+ textStyle: AppType.monoMeta(),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ 6,
+ ),
+ ),
+ ),
+ child: Text(switch (filter) {
+ SessionFilter.all =>
+ 'All ${all.length}',
+ SessionFilter.needsInput =>
+ 'Needs input $needsInput',
+ SessionFilter.running =>
+ 'Running $running',
+ SessionFilter.paused =>
+ 'Paused $paused',
+ }),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ MenuAnchor(
+ controller: _sortMenu,
+ menuChildren: [
+ for (final sort in SessionSort.values)
+ AppMenuItem(
+ label: sort.label,
+ selected: _sort == sort,
+ onPressed: () {
+ _sortMenu.close();
+ setState(() {
+ _sort = sort;
+ _selected = null;
+ });
+ },
+ ),
+ ],
+ builder: (context, controller, child) => Tooltip(
+ message: 'Sort harnesses',
+ child: TextButton.icon(
+ onPressed: () => controller.isOpen
+ ? controller.close()
+ : controller.open(),
+ style: TextButton.styleFrom(
+ foregroundColor: AppPalette.textSecondary,
+ minimumSize: const Size(0, 30),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8,
+ ),
+ textStyle: AppType.monoMeta(),
+ ),
+ icon: const Icon(
+ LucideIcons.arrowDownWideNarrow,
+ size: 13,
+ ),
+ label: Text(
+ _sort == SessionSort.recent
+ ? 'Recent'
+ : _sort.label,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ Divider(
+ height: 1,
+ color: AppPalette.textPrimary.withValues(alpha: .08),
+ ),
+ Flexible(
+ child: rows.isEmpty
+ ? Padding(
+ padding: const EdgeInsets.symmetric(
+ vertical: 42,
+ horizontal: 24,
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ LucideIcons.layers,
+ size: 25,
+ color: AppPalette.textFaint,
+ ),
+ const SizedBox(height: 12),
+ Text(
+ all.isEmpty
+ ? 'Your harnesses live here'
+ : showingQuestions &&
+ _search.text.trim().isEmpty
+ ? 'No harnesses need your input'
+ : 'No matching harnesses',
+ style: AppType.label(height: 1.3),
+ ),
+ if (!showingQuestions ||
+ _search.text.trim().isNotEmpty ||
+ all.isEmpty) ...[
+ const SizedBox(height: 6),
+ Text(
+ all.isEmpty
+ ? 'Open a harness to get started.'
+ : 'Try another search or filter.',
+ style: AppType.body(
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ],
+ ],
+ ),
+ )
+ : Scrollbar(
+ controller: _scroll,
+ child: ListView.builder(
+ controller: _scroll,
+ shrinkWrap: true,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8,
+ vertical: 6,
+ ),
+ itemCount: rows.length,
+ itemBuilder: (context, index) {
+ final row = rows[index];
+ final pendingStop =
+ (widget.app.pendingAgentPause(
+ row.machineId,
+ row.agent.id,
+ ) ??
+ widget.app.pendingAgentStop(
+ row.machineId,
+ row.agent.id,
+ )) !=
+ null;
+ final pendingResume = widget.app
+ .restartAttempt(row.machineId, row.agent.id)
+ .busy;
+ final busy =
+ _pending.containsKey(row.id) ||
+ pendingStop ||
+ pendingResume ||
+ _opening == row.id;
+ return _SessionRow(
+ key: _rowKeys.putIfAbsent(
+ row.id,
+ () => GlobalKey(),
+ ),
+ row: row,
+ height: rowHeight,
+ now: now,
+ showQuestion: showingQuestions,
+ selected:
+ _selected != null && selected?.id == row.id,
+ busy: busy,
+ pendingLabel: _opening == row.id
+ ? 'Opening…'
+ : pendingStop
+ ? 'Pausing…'
+ : row.agent.isStopped
+ ? 'Resuming…'
+ : 'Pausing…',
+ error: _errors[row.id],
+ onOpen: () =>
+ _open(row, answering: row.needsInput),
+ onAnswer: () => _open(row, answering: true),
+ onToggle: () => _toggle(row),
+ );
+ },
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _SessionRow extends StatelessWidget {
+ const _SessionRow({
+ super.key,
+ required this.row,
+ required this.height,
+ required this.now,
+ required this.showQuestion,
+ required this.selected,
+ required this.busy,
+ required this.pendingLabel,
+ required this.onOpen,
+ required this.onToggle,
+ required this.onAnswer,
+ this.error,
+ });
+ final HarnessSession row;
+ final double height;
+ final DateTime now;
+ final bool selected, busy, showQuestion;
+ final String pendingLabel;
+ final VoidCallback onOpen, onToggle, onAnswer;
+ final String? error;
+
+ @override
+ Widget build(BuildContext context) {
+ // Login or permission review may be required before a native resume hook.
+ final canOpen =
+ row.canOpen &&
+ (!busy ||
+ (row.agent.terminalAvailable &&
+ row.agent.launchState == 'starting'));
+ // Play/pause carries normal state; only exceptions need another label.
+ final attention = switch (row.status) {
+ 'Ready' || 'Paused' || 'Working' || 'Needs input' => null,
+ final status => status,
+ };
+ final activity = row.lastActiveAt == null
+ ? 'Last activity unavailable'
+ : 'Last active ${harnessActivityAge(row.lastActiveAt, now)} ago';
+ Widget detail(IconData icon, String text, Color color, {String? tooltip}) =>
+ Flexible(
+ child: Tooltip(
+ message: tooltip ?? text,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(icon, size: 11, color: color),
+ const SizedBox(width: 5),
+ Flexible(
+ child: Text(
+ text,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.monoMeta(color: color, height: 1.3),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ return Padding(
+ padding: const EdgeInsets.symmetric(vertical: 1),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: selected
+ ? AppPalette.textPrimary.withValues(alpha: .06)
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Column(
+ children: [
+ SizedBox(
+ height: height,
+ child: Row(
+ children: [
+ Expanded(
+ child: Semantics(
+ key: ValueKey('session-open:${row.id}'),
+ selected: selected,
+ container: true,
+ button: true,
+ enabled: canOpen,
+ label:
+ '${row.agent.isStopped ? 'Resume and open' : 'Open'} ${row.agent.displayName}',
+ value: [
+ row.machine.machine.displayName,
+ row.project?.label,
+ row.project?.shownBranch,
+ row.question?.prompt,
+ activity,
+ busy ? pendingLabel : row.status,
+ ].whereType<String>().join(', '),
+ onTap: canOpen ? onOpen : null,
+ excludeSemantics: true,
+ child: InkWell(
+ onTap: canOpen ? onOpen : null,
+ borderRadius: BorderRadius.circular(8),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(12, 10, 6, 10),
+ child: Row(
+ children: [
+ EngineMark(
+ engine: row.agent.identityEngine,
+ size: 22,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Flexible(
+ child: Tooltip(
+ message: row.agent.displayName,
+ child: Text(
+ row.agent.displayName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.label(height: 1.3),
+ ),
+ ),
+ ),
+ if (attention != null && !busy)
+ Padding(
+ padding: const EdgeInsets.only(
+ left: 12,
+ ),
+ child: Text(
+ attention,
+ style: AppType.monoMeta(
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 6),
+ Row(
+ children: [
+ detail(
+ LucideIcons.monitor,
+ row.machine.machine.displayName,
+ AppPalette.textSecondary,
+ ),
+ if (row.project
+ case final project?) ...[
+ const SizedBox(width: 12),
+ detail(
+ LucideIcons.folder,
+ project.label,
+ const Color(0xff79bbaf),
+ tooltip: project.cwd,
+ ),
+ if (project.shownBranch
+ case final branch?) ...[
+ const SizedBox(width: 12),
+ detail(
+ LucideIcons.gitBranch,
+ branch,
+ const Color(0xff8dbb79),
+ ),
+ ],
+ ],
+ const SizedBox(width: 12),
+ detail(
+ LucideIcons.clock3,
+ harnessActivityAge(
+ row.lastActiveAt,
+ now,
+ ),
+ AppPalette.textSecondary,
+ tooltip: row.lastActiveAt == null
+ ? activity
+ : 'Last active ${row.lastActiveAt!.toLocal()}',
+ ),
+ ],
+ ),
+ if (showQuestion)
+ if (row.question
+ case final question?) ...[
+ const SizedBox(height: 6),
+ Tooltip(
+ message: question.prompt,
+ child: Text(
+ question.prompt.replaceAll(
+ RegExp(r'\s+'),
+ ' ',
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.monoMeta(
+ color: const Color(0xffd9ad70),
+ height: 1.3,
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ if (row.needsInput)
+ IconButton(
+ key: ValueKey('session-answer:${row.id}'),
+ tooltip: 'Needs input: ${row.question!.prompt}',
+ onPressed: canOpen ? onAnswer : null,
+ color: const Color(0xffd9ad70),
+ icon: Icon(
+ LucideIcons.messageCircleQuestionMark,
+ size: 17,
+ semanticLabel:
+ 'Needs input for ${row.agent.displayName}',
+ ),
+ ),
+ Tooltip(
+ message: busy
+ ? pendingLabel
+ : row.controlUnavailable ??
+ (row.agent.isStopped
+ ? 'Resume harness'
+ : 'Pause harness'),
+ child: SizedBox(
+ width: 40,
+ height: 40,
+ child: busy
+ ? Semantics(
+ liveRegion: true,
+ label: '$pendingLabel ${row.agent.displayName}',
+ child: Center(
+ child: SizedBox(
+ width: 15,
+ height: 15,
+ child: CircularProgressIndicator(
+ strokeWidth: 1.5,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ )
+ : IconButton(
+ key: ValueKey('session-toggle:${row.id}'),
+ onPressed: row.canControl ? onToggle : null,
+ icon: Icon(
+ row.agent.isStopped
+ ? LucideIcons.play
+ : LucideIcons.pause,
+ size: 17,
+ semanticLabel:
+ '${row.agent.isStopped ? 'Resume' : 'Pause'} ${row.agent.displayName}',
+ ),
+ style: IconButton.styleFrom(
+ foregroundColor: AppPalette.textPrimary,
+ disabledForegroundColor: AppPalette.textFaint
+ .withValues(alpha: .4),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 6),
+ ],
+ ),
+ ),
+ if (error != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(46, 0, 12, 12),
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ error!,
+ style: AppType.body(color: const Color(0xffe4a19b)),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 2f18e63b4..bf446e1f2 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -35,6 +35,7 @@ import 'web_pane_panel.dart';
import 'pane_resize_handle.dart';
import 'box_chrome.dart';
import 'pane_split_edges.dart';
+import 'pane_minimize.dart';
/// Terminal views arranged by the chosen preset. Swarms keep each view under
/// one stable parent as its rectangle, visibility and keyboard focus change.
@@ -1172,11 +1173,14 @@ class _PaneCell extends StatelessWidget {
@override
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
- return LayoutBuilder(
- builder: (context, constraints) {
- if (visible) pane.lastViewSize = constraints.biggest;
- return _build(context);
- },
+ return PaneMinimizeSurface(
+ paneId: pane.id,
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ if (visible) pane.lastViewSize = constraints.biggest;
+ return _build(context);
+ },
+ ),
);
}
@@ -1338,7 +1342,15 @@ class _PaneContent extends StatelessWidget {
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
final machine = notifier.stateOf(pane.machineId);
- void close() => notifier.closePane(pane.id);
+ void close() {
+ final minimize = PaneMinimizeScope.maybeOf(context);
+ if (minimize != null) {
+ minimize.close(pane);
+ } else {
+ notifier.closePane(pane.id);
+ }
+ }
+
if (pane.sharedHarness case final grant?) {
return SharedHarnessPanel(
key: ValueKey('shared-pane-${pane.id}'),
diff --git a/desktop/lib/widgets/pane_minimize.dart b/desktop/lib/widgets/pane_minimize.dart
new file mode 100644
index 000000000..ea4df5be3
--- /dev/null
+++ b/desktop/lib/widgets/pane_minimize.dart
@@ -0,0 +1,205 @@
+import 'dart:math' as math;
+import 'dart:typed_data';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+
+import '../state/terminal_pane.dart';
+
+/// A GPU snapshot bends into the manager after the pane releases input.
+/// Capturing never resizes the terminal or stops its process.
+class PaneMinimizeController extends ChangeNotifier {
+ PaneMinimizeController({required TickerProvider vsync}) {
+ animation = AnimationController(
+ vsync: vsync,
+ duration: const Duration(milliseconds: 520),
+ )..addListener(notifyListeners);
+ }
+ late final AnimationController animation;
+ final _boundaries = <int, GlobalKey>{};
+ ui.Image? snapshot;
+ int? paneId;
+ Rect source = Rect.zero;
+ Offset target = Offset.zero;
+
+ bool capture(TerminalPane pane) {
+ final box = pane.cellKey.currentContext?.findRenderObject();
+ if (box is! RenderBox || !box.hasSize || box.size.isEmpty) return false;
+ source = box.localToGlobal(Offset.zero) & box.size;
+ target = source.center;
+ final boundary = _boundaries[pane.id]?.currentContext?.findRenderObject();
+ if (boundary is RenderRepaintBoundary) {
+ try {
+ // Bound texture memory even on a large Retina display. No PNG encoding
+ // or CPU readback, and no repeated capture while the pane is moving.
+ final ratio = math.min(
+ 2.0,
+ 1600 / math.max(source.width, source.height),
+ );
+ snapshot = boundary.toImageSync(pixelRatio: ratio);
+ } catch (_) {
+ // An unpainted/offscreen pane closes immediately without a snapshot.
+ }
+ }
+ if (snapshot == null) return false;
+ paneId = pane.id;
+ return true;
+ }
+
+ Future<void> animate(Offset destination) async {
+ target = destination;
+ await animation.forward(from: 0).orCancel;
+ }
+
+ void reset() {
+ paneId = null;
+ snapshot?.dispose();
+ snapshot = null;
+ animation.reset();
+ notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ snapshot?.dispose();
+ animation.dispose();
+ super.dispose();
+ }
+}
+
+class PaneMinimizeScope extends InheritedWidget {
+ const PaneMinimizeScope({
+ super.key,
+ required this.controller,
+ required this.close,
+ required super.child,
+ });
+ final PaneMinimizeController controller;
+ final Future<void> Function(TerminalPane) close;
+ static PaneMinimizeScope? maybeOf(BuildContext context) =>
+ context.dependOnInheritedWidgetOfExactType<PaneMinimizeScope>();
+ @override
+ bool updateShouldNotify(PaneMinimizeScope oldWidget) =>
+ controller != oldWidget.controller;
+}
+
+/// The upper edge reaches for the icon first; the rest follows through a smooth
+/// neck. Every horizontal slice stays ordered, so the texture never folds over.
+Rect paneMinimizeSlice(Size size, Offset target, double progress, double v) {
+ final t = progress.clamp(0.0, 1.0);
+ final pull = Curves.easeOutCubic.transform(t);
+ final rise = Curves.easeInCubic.transform(t);
+ final top = (target.dy - 11) * pull;
+ final bottom = size.height + (target.dy + 11 - size.height) * rise;
+ final wave = ((t - v * .28) / (1 - v * .28)).clamp(0.0, 1.0);
+ final narrow = Curves.easeOutCubic.transform(wave);
+ final width = size.width + (22 - size.width) * narrow;
+ final center = size.width / 2 + (target.dx - size.width / 2) * narrow;
+ return Rect.fromLTWH(center - width / 2, top + (bottom - top) * v, width, 0);
+}
+
+class _GeniePainter extends CustomPainter {
+ _GeniePainter(this.controller) : super(repaint: controller.animation);
+ final PaneMinimizeController controller;
+ static const _bands = 48;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final image = controller.snapshot;
+ if (image == null) return;
+ final t = controller.animation.value;
+ final target = controller.target - controller.source.topLeft;
+ final positions = <Offset>[];
+ final texture = <Offset>[];
+ for (var i = 0; i <= _bands; i++) {
+ final v = i / _bands;
+ final slice = paneMinimizeSlice(size, target, t, v);
+ positions.addAll([slice.topLeft, slice.topRight]);
+ texture.addAll([
+ Offset(0, image.height * v),
+ Offset(image.width.toDouble(), image.height * v),
+ ]);
+ }
+ final vertices = ui.Vertices(
+ ui.VertexMode.triangleStrip,
+ positions,
+ textureCoordinates: texture,
+ );
+ final opacity = 1 - Curves.easeIn.transform(((t - .86) / .14).clamp(0, 1));
+ final paint = Paint()
+ ..color = Colors.white.withValues(alpha: opacity)
+ ..filterQuality = FilterQuality.medium
+ ..shader = ImageShader(
+ image,
+ TileMode.clamp,
+ TileMode.clamp,
+ Float64List.fromList(Matrix4.identity().storage),
+ );
+ canvas.drawVertices(vertices, BlendMode.modulate, paint);
+ vertices.dispose();
+ }
+
+ @override
+ bool shouldRepaint(_GeniePainter oldDelegate) =>
+ controller != oldDelegate.controller;
+}
+
+class PaneMinimizeSurface extends StatefulWidget {
+ const PaneMinimizeSurface({
+ super.key,
+ required this.paneId,
+ required this.child,
+ });
+ final int paneId;
+ final Widget child;
+ @override
+ State<PaneMinimizeSurface> createState() => _PaneMinimizeSurfaceState();
+}
+
+class _PaneMinimizeSurfaceState extends State<PaneMinimizeSurface> {
+ final _boundary = GlobalKey();
+ PaneMinimizeController? _controller;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final controller = PaneMinimizeScope.maybeOf(context)?.controller;
+ if (_controller == controller) return;
+ _controller?._boundaries.remove(widget.paneId);
+ _controller = controller;
+ controller?._boundaries[widget.paneId] = _boundary;
+ }
+
+ @override
+ void didUpdateWidget(PaneMinimizeSurface oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.paneId != widget.paneId) {
+ _controller?._boundaries.remove(oldWidget.paneId);
+ _controller?._boundaries[widget.paneId] = _boundary;
+ }
+ }
+
+ @override
+ void dispose() {
+ _controller?._boundaries.remove(widget.paneId);
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) =>
+ RepaintBoundary(key: _boundary, child: widget.child);
+}
+
+/// The departing pixels have no focus, semantics, or pointer target.
+class PaneMinimizeSnapshot extends StatelessWidget {
+ const PaneMinimizeSnapshot({super.key, required this.controller});
+ final PaneMinimizeController controller;
+
+ @override
+ Widget build(BuildContext context) => IgnorePointer(
+ child: ExcludeSemantics(
+ child: CustomPaint(painter: _GeniePainter(controller)),
+ ),
+ );
+}
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 81ee77a64..02048f346 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -94,6 +94,17 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
let state = call.arguments as? [String: Any] ?? [:]
self.updateMachines(state["machines"] as? [[String: Any]] ?? [])
result(nil)
+ case "sessionsAnchor":
+ guard let content = self.window?.contentViewController?.view else { result(nil); return }
+ let rect = self.strip.sessionsButton.convert(self.strip.sessionsButton.bounds, to: content)
+ result([
+ "x": rect.midX,
+ "y": content.isFlipped ? rect.midY : content.bounds.height - rect.midY,
+ "reduceMotion": NSWorkspace.shared.accessibilityDisplayShouldReduceMotion,
+ ])
+ case "sessionMinimized":
+ self.strip.sessionsButton.receiveSession()
+ result(nil)
case "modelsState":
let state = call.arguments as? [String: Any] ?? [:]
self.updateModels(
@@ -134,7 +145,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
private func sendTabAction(_ method: String, arguments: Any?) {
- guard ["select", "close", "new", "rename", "commands", "notifications", "store", "addAgent", "newAgent", "newTerminal", "cloneAgent", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
+ guard ["select", "close", "new", "rename", "commands", "notifications", "store", "sessions", "addAgent", "newAgent", "newTerminal", "cloneAgent", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
channel.invokeMethod(method, arguments: arguments)
return
}
@@ -318,7 +329,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
if let view = main.item(withTitle: "View")?.submenu {
view.addItem(.separator())
- add(view, "Agents Needing Input…", "i", "notifications", [.command, .shift])
+ add(view, "Harnesses Needing Input…", "i", "notifications", [.command, .shift])
}
modelsMenu.autoenablesItems = false
modelsMenu.delegate = self
@@ -1438,15 +1449,51 @@ private final class SwarmStoreButton: SwarmIconButton {
}
}
-private final class SwarmNotificationButton: SwarmIconButton {
- var hasAttention = false { didSet { needsDisplay = true } }
+private final class SwarmSessionsButton: SwarmIconButton {
+ var running = 0 { didSet { needsDisplay = true } }
+ var attention = 0 { didSet { needsDisplay = true } }
+ var expanded = false { didSet { needsDisplay = true } }
+
+ var attentionLabel: String? {
+ attention > 0 ? (attention > 99 ? "99+" : String(attention)) : nil
+ }
+
+ func badgeFrame(textWidth: CGFloat) -> NSRect {
+ let width = max(12, ceil(textWidth) + 5)
+ return NSRect(x: bounds.maxX - width,
+ y: isFlipped ? bounds.minY : bounds.maxY - 12, width: width, height: 12)
+ }
+
override func draw(_ dirtyRect: NSRect) {
+ if expanded {
+ NSColor.white.withAlphaComponent(0.08).setFill()
+ NSBezierPath(roundedRect: bounds.insetBy(dx: 1, dy: 1), xRadius: 7, yRadius: 7).fill()
+ }
super.draw(dirtyRect)
- if hasAttention {
- NSColor.systemOrange.setFill()
- NSBezierPath(ovalIn: NSRect(x: bounds.midX + 4, y: bounds.midY + 5, width: 5, height: 5)).fill()
+ if let label = attentionLabel {
+ let attributes: [NSAttributedString.Key: Any] = [
+ .font: NSFont.monospacedDigitSystemFont(ofSize: 9, weight: .semibold),
+ .foregroundColor: NSColor.white,
+ ]
+ let text = label as NSString
+ let size = text.size(withAttributes: attributes)
+ let badge = badgeFrame(textWidth: size.width)
+ NSColor.systemRed.withAlphaComponent(isEnabled ? 1 : 0.45).setFill()
+ NSBezierPath(roundedRect: badge, xRadius: 6, yRadius: 6).fill()
+ text.draw(at: NSPoint(x: badge.midX - size.width / 2, y: badge.midY - size.height / 2),
+ withAttributes: attributes)
}
}
+
+ func receiveSession() {
+ guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { return }
+ wantsLayer = true
+ let pulse = CAKeyframeAnimation(keyPath: "transform.scale")
+ pulse.values = [1, 1.18, 1]
+ pulse.keyTimes = [0, 0.4, 1]
+ pulse.duration = 0.24
+ layer?.add(pulse, forKey: "session-arrived")
+ }
}
private final class SwarmStripScrollView: NSScrollView {
@@ -1471,8 +1518,8 @@ private final class SwarmTabStrip: NSView {
private let scroll = SwarmStripScrollView()
private let document = NSView()
fileprivate let newButton = SwarmIconButton()
- fileprivate let notificationButton = SwarmNotificationButton()
fileprivate let storeButton = SwarmStoreButton(title: "Harness Store", target: nil, action: nil)
+ fileprivate let sessionsButton = SwarmSessionsButton()
private var tabs: [SwarmTabButton] = []
private let icons = SwarmHistoryIcons()
private var activeId = ""
@@ -1520,8 +1567,9 @@ private final class SwarmTabStrip: NSView {
button(newButton, "plus", "New Tab", #selector(newSwarm))
newButton.setAccessibilityLabel("New Tab")
newButton.isEnabled = false
- button(notificationButton, "bell", "Notifications", #selector(openNotifications))
- notificationButton.isEnabled = false
+ button(sessionsButton, "terminal", "Harnesses", #selector(openSessions))
+ sessionsButton.isEnabled = false
+ sessionsButton.toolTip = "Harnesses"
newButton.toolTip = "New Tab ⌘T"
storeButton.isBordered = false
storeButton.palette = palette
@@ -1533,7 +1581,7 @@ private final class SwarmTabStrip: NSView {
storeButton.toolTip = "Harness Store ⌘S"
storeButton.setAccessibilityLabel("Harness Store")
addSubview(storeButton)
- setAccessibilityChildren([notificationButton, scroll, newButton, storeButton])
+ setAccessibilityChildren([scroll, newButton, sessionsButton, storeButton])
registerForDraggedTypes([swarmPasteboardType])
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -1542,8 +1590,8 @@ private final class SwarmTabStrip: NSView {
let nextPalette = SwarmNativePalette(values)
guard nextPalette != palette else { return }
palette = nextPalette
- notificationButton.contentTintColor = palette.accent
newButton.contentTintColor = palette.accent
+ sessionsButton.contentTintColor = palette.accent
storeButton.palette = palette
for tab in tabs { tab.palette = palette }
needsDisplay = true
@@ -1624,11 +1672,17 @@ private final class SwarmTabStrip: NSView {
// Moving frames alone leaves AppKit's child traversal in insertion order.
document.setAccessibilityChildren(tabs)
newButton.isEnabled = actionsEnabled
- notificationButton.isEnabled = actionsEnabled
storeButton.isEnabled = actionsEnabled
+ sessionsButton.isEnabled = actionsEnabled
+ sessionsButton.running = state["runningSessions"] as? Int ?? 0
+ sessionsButton.expanded = state["sessionsOpen"] as? Bool == true
+ let expandedState = sessionsButton.expanded ? "Expanded" : "Collapsed"
+ sessionsButton.toolTip = sessionsButton.running > 0 ? "Harnesses · \(sessionsButton.running) running" : "Harnesses"
let attention = state["attention"] as? Int ?? 0
- notificationButton.hasAttention = attention > 0
- notificationButton.setAccessibilityLabel(attention > 0 ? "\(attention) agents need input" : "Notifications")
+ sessionsButton.attention = attention
+ let attentionState = "\(attention) \(attention == 1 ? "needs" : "need") input"
+ sessionsButton.setAccessibilityValue(attention > 0 ? "\(expandedState), \(attentionState)" : expandedState)
+ if attention > 0 { sessionsButton.toolTip = "Harnesses · \(attentionState)" }
needsLayout = true
layoutSubtreeIfNeeded()
if ids != previousOrder {
@@ -1650,7 +1704,7 @@ private final class SwarmTabStrip: NSView {
let activeWasVisible = active.map { scroll.documentVisibleRect.intersects($0.frame) } ?? false
let previousScrollSize = scroll.frame.size
let previousDocumentSize = document.frame.size
- let leading: CGFloat = 36
+ let leading: CGFloat = 0
let spacious = bounds.width >= 480
let trailing: CGFloat = spacious ? 12 : 8
let storeWidth = storeButton.preferredWidth
@@ -1659,7 +1713,7 @@ private final class SwarmTabStrip: NSView {
// where a full strip can still be dragged and double-clicked to zoom
// (owner, 2026-09-15); tabs shrink and then scroll instead of taking it.
let grip: CGFloat = spacious ? 84 : 44
- let available = max(32, bounds.width - leading - trailing - (newButton.isHidden ? 0 : 36) - grip - storeWidth - 8)
+ let available = max(32, bounds.width - leading - trailing - (newButton.isHidden ? 0 : 36) - grip - storeWidth - 44)
// As in Chrome, tabs keep shrinking until they are only their mark, so thirty tabs still sit in
// one strip with nothing hidden; only past that does the strip scroll (the wheel scrolls it).
let width = min(220, max(min(SwarmTabButton.minimumWidth, available), available / CGFloat(max(1, tabs.count))))
@@ -1673,9 +1727,9 @@ private final class SwarmTabStrip: NSView {
tab.contentCenterY = bounds.midY
}
let buttonY = (bounds.height - 28) / 2
- notificationButton.frame = NSRect(x: 0, y: buttonY, width: 28, height: 28)
newButton.frame = NSRect(x: leading + occupied + 4, y: buttonY, width: 28, height: 28)
storeButton.frame = NSRect(x: bounds.width - trailing - storeWidth, y: buttonY, width: storeWidth, height: 28)
+ sessionsButton.frame = NSRect(x: storeButton.frame.minX - 36, y: buttonY, width: 28, height: 28)
let geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSize
if let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {
document.scrollToVisible(active.frame)
@@ -1713,12 +1767,12 @@ private final class SwarmTabStrip: NSView {
@objc private func newSwarm() {
if actionsEnabled && newButton.isEnabled { emit?("new", nil) }
}
- @objc private func openNotifications() {
- if actionsEnabled { emit?("notifications", nil) }
- }
@objc private func openStore() {
if actionsEnabled { emit?("store", nil) }
}
+ @objc private func openSessions() {
+ if actionsEnabled { emit?("sessions", nil) }
+ }
private func draggedTab(_ sender: NSDraggingInfo) -> SwarmTabButton? {
guard actionsEnabled, sender.draggingSourceOperationMask.contains(.move),
diff --git a/desktop/test/agent_pause_state_test.dart b/desktop/test/agent_pause_state_test.dart
new file mode 100644
index 000000000..b0a27f9b3
--- /dev/null
+++ b/desktop/test/agent_pause_state_test.dart
@@ -0,0 +1,163 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/restart_connection.dart';
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late AppNotifier app;
+ late RestartConnection connection;
+ const source = Agent(
+ id: 'a0',
+ name: 'Disposable harness',
+ engine: 'codex',
+ sessionId: 'original-history',
+ terminalAvailable: true,
+ );
+ Map<String, dynamic> inventory({bool paused = true}) => {
+ 'agents': [
+ {
+ 'id': source.id,
+ 'name': source.name,
+ 'engine': source.engine,
+ 'sessionId': source.sessionId,
+ 'status': paused ? 'stopped' : 'active',
+ 'terminal': {'available': !paused},
+ },
+ ],
+ };
+ setUp(() {
+ connection = RestartConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!
+ ..agents = [source]
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ });
+ tearDown(() => app.dispose());
+
+ test('thirty pause/resume cycles preserve identity and issue one command per transition', () async {
+ for (var cycle = 0; cycle < 30; cycle++) {
+ connection.inventory = Completer<Map<String, dynamic>>()
+ ..complete(inventory());
+ final pause = app.pauseAgent('m', 'a0');
+ expect(app.pauseAgent('m', 'a0'), same(pause));
+ connection.stopReplies.last.complete({'deleted': true});
+ expect(await pause, isNull);
+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
+ final resume = app.resumeAgent('m', 'a0');
+ expect(app.resumeAgent('m', 'a0'), same(resume));
+ connection.restartReplies.last.complete(
+ restartReceipt(
+ connection.requests.last['creationId'] as String,
+ sessionId: source.sessionId,
+ ),
+ );
+ expect((await resume).error, isNull);
+ expect(app.stateOf('m')!.agents.single.sessionId, source.sessionId);
+ expect(app.stateOf('m')!.agents.single.isStopped, isFalse);
+ }
+ expect(connection.stops, hasLength(30));
+ expect(connection.types, List.filled(30, 'agent_resume'));
+ expect(connection.checks, isEmpty);
+ });
+
+ test(
+ 'a confirmed pause remains in inventory when its refresh fails',
+ () async {
+ connection.inventory = Completer<Map<String, dynamic>>();
+ final pause = app.pauseAgent('m', 'a0');
+ connection.stopReplies.single.complete({'deleted': true});
+ await Future<void>.delayed(Duration.zero);
+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
+ expect(app.pendingAgentPause('m', 'a0'), same(pause));
+ expect(
+ (await app.resumeAgent('m', 'a0')).error,
+ contains('still pausing'),
+ );
+ expect(connection.requests, isEmpty);
+ connection.inventory!.completeError(StateError('inventory unavailable'));
+ expect(await pause, isNull);
+ expect(app.stateOf('m')!.agents.single.sessionId, source.sessionId);
+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
+ expect(app.pendingAgentPause('m', 'a0'), isNull);
+ },
+ );
+
+ test(
+ 'a lost stop reply resolves through inventory without another stop',
+ () async {
+ connection.inventory = Completer<Map<String, dynamic>>()
+ ..complete(inventory());
+ final pause = app.pauseAgent('m', 'a0');
+ connection.stopReplies.single.completeError(
+ const WsRequestTimeout('agent_delete'),
+ );
+ expect(await pause, isNull);
+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
+ expect(connection.stops, ['a0']);
+ },
+ );
+
+ test(
+ 'a native refusal keeps the live harness and its actionable error',
+ () async {
+ connection.inventory = Completer<Map<String, dynamic>>()
+ ..complete(inventory(paused: false));
+ final pause = app.pauseAgent('m', 'a0');
+ connection.stopReplies.single.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_delete_result',
+ code: 'STOP_UNCONFIRMED',
+ detail: 'Could not confirm that the harness stopped.',
+ ),
+ );
+ expect(
+ await pause,
+ contains('Could not confirm that the harness stopped.'),
+ );
+ expect(app.stateOf('m')!.agents.single.isStopped, isFalse);
+ expect(connection.stops, ['a0']);
+ },
+ );
+
+ test(
+ 'an ambiguous stop reply cannot turn a live harness into paused',
+ () async {
+ connection.inventory = Completer<Map<String, dynamic>>()
+ ..complete(inventory(paused: false));
+ final pause = app.pauseAgent('m', 'a0');
+ connection.stopReplies.single.complete({});
+ expect(await pause, contains('Could not confirm'));
+ expect(app.stateOf('m')!.agents.single.isStopped, isFalse);
+ },
+ );
+
+ test('pause never sends a command for an unsupported or missing saved conversation', () async {
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Other engine',
+ engine: 'opencode',
+ sessionId: 'saved',
+ terminalAvailable: true,
+ ),
+ ];
+ expect(await app.pauseAgent('m', 'a0'), isNotNull);
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Not saved yet',
+ engine: 'claude',
+ terminalAvailable: true,
+ ),
+ ];
+ expect(await app.pauseAgent('m', 'a0'), isNotNull);
+ expect(connection.stops, isEmpty);
+ });
+}
diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dart
index 8de012353..5207a5f34 100644
--- a/desktop/test/first_workspace_test.dart
+++ b/desktop/test/first_workspace_test.dart
@@ -514,10 +514,7 @@ void main() {
find.byKey(const ValueKey('swarm-new-pane-button')),
findsNothing,
);
- expect(
- find.byKey(const ValueKey('swarm-notifications-button')),
- findsOneWidget,
- );
+ expect(find.byTooltip('Harnesses'), findsOneWidget);
expect(
find.byKey(const ValueKey('swarm-new-harness-button')),
findsNothing,
diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dart
new file mode 100644
index 000000000..f7bcc2d23
--- /dev/null
+++ b/desktop/test/harness_session_manager_test.dart
@@ -0,0 +1,895 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' show SemanticsAction;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_sessions.dart';
+import 'package:harness/state/pending_question.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/widgets/harness_session_manager.dart';
+import 'package:harness/widgets/pane_minimize.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/restart_connection.dart';
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+const _project = AgentProject(
+ name: 'autonomous-harness',
+ cwd: '/work/autonomous-harness',
+ branch: 'fix/file-menu-order',
+);
+const _running = Agent(
+ id: 'a0',
+ name: 'Font styling review',
+ engine: 'claude',
+ sessionId: 'conversation',
+ terminalAvailable: true,
+ project: _project,
+);
+const _paused = Agent(
+ id: 'saved',
+ name: 'Landing page polish',
+ engine: 'codex',
+ sessionId: 'saved-conversation',
+ status: 'stopped',
+ project: AgentProject(
+ name: 'website',
+ cwd: '/work/website',
+ branch: 'design/landing',
+ ),
+);
+
+void main() {
+ late AppNotifier app;
+ late RestartConnection connection;
+ setUp(() {
+ connection = RestartConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.machineStates['m']!
+ ..machine = const Machine(
+ machineId: 'm',
+ name: 'iMac — Office',
+ authMode: MachineAuthMode.remote,
+ )
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true
+ ..agents = [_running, _paused];
+ });
+ tearDown(() => app.dispose());
+
+ Finder toggle(String id) =>
+ find.byKey(ValueKey('session-toggle:${agentDestinationId('m', id)}'));
+ Future<void> open(WidgetTester tester) async {
+ await mount(tester, app);
+ await tester.tap(find.byTooltip('Harnesses'));
+ await tester.pumpAndSettle();
+ }
+
+ PendingQuestion question(String id, {String request = 'question'}) =>
+ PendingQuestion(
+ machineId: 'm',
+ agentId: id,
+ requestId: request,
+ answerKey: 'folder',
+ prompt: 'Use the shared cache?',
+ options: ['Yes', 'No'],
+ multi: false,
+ since: DateTime(2026, 9, 22),
+ );
+
+ test(
+ 'activity age is compact and safely handles old daemons and clock skew',
+ () {
+ final now = DateTime(2026, 9, 22, 12);
+ expect(harnessActivityAge(null, now), '—');
+ expect(
+ harnessActivityAge(now.add(const Duration(minutes: 4)), now),
+ '0m',
+ );
+ for (final sample in [
+ (59, '0m'),
+ (300, '5m'),
+ (3599, '59m'),
+ (3600, '1h'),
+ (86400, '1d'),
+ (172800, '2d'),
+ ]) {
+ expect(
+ harnessActivityAge(now.subtract(Duration(seconds: sample.$1)), now),
+ sample.$2,
+ );
+ }
+ final parsed = Agent.fromJson({
+ 'id': 'fresh',
+ 'updatedAt': now.toIso8601String(),
+ });
+ expect(parsed.lastActivityAt, now);
+ expect(parsed.copyWith(name: 'Renamed').lastActivityAt, now);
+ expect(
+ Agent.fromJson({'id': 'legacy', 'updatedAt': 'invalid'}).lastActivityAt,
+ isNull,
+ );
+ },
+ );
+
+ test('recent follows real activity before navigation recency', () {
+ app.machineStates['m']!.agents = [
+ Agent.fromJson({'id': 'older', 'updatedAt': '2026-09-21T10:00:00Z'}),
+ Agent.fromJson({'id': 'newer', 'updatedAt': '2026-09-22T10:00:00Z'}),
+ const Agent(id: 'unknown', name: 'Unknown'),
+ ];
+ expect(
+ visibleHarnessSessions(
+ harnessSessions(app),
+ recent: [agentDestinationId('m', 'older')],
+ ).map((row) => row.agent.id),
+ ['newer', 'older', 'unknown'],
+ );
+ });
+
+ test('attention filters live questions, retains missing agents, excludes paused history', () {
+ app.machineStates['m']!.blockedAgents.addAll({
+ 'a0': question('a0'),
+ 'saved': question('saved'),
+ 'missing': question('missing'),
+ });
+ final rows = visibleHarnessSessions(
+ harnessSessions(app),
+ filter: SessionFilter.needsInput,
+ );
+ expect(rows.map((row) => row.agent.id), containsAll(['a0', 'missing']));
+ expect(rows, hasLength(2));
+ expect(
+ rows.singleWhere((row) => row.agent.id == 'missing').canControl,
+ isFalse,
+ );
+ expect(
+ rows.singleWhere((row) => row.agent.id == 'missing').canOpen,
+ isFalse,
+ );
+ expect(
+ visibleHarnessSessions(rows, query: 'office shared cache'),
+ hasLength(2),
+ );
+ });
+
+ testWidgets(
+ 'Needs input exposes the question and opens its existing pane without pausing',
+ (tester) async {
+ await app.addAgentToSwarm('m', 'a0');
+ app.machineStates['m']!.blockedAgents['a0'] = question('a0');
+ await mount(tester, app);
+ await tester.tap(find.byTooltip('Harnesses'));
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(
+ find.byKey(const ValueKey('swarm-notifications-button')),
+ findsNothing,
+ );
+ final managerIcon = tester.getRect(find.byTooltip('Harnesses'));
+ expect(
+ managerIcon.right,
+ lessThan(
+ tester.getRect(find.byKey(const ValueKey('swarm-store-button'))).left,
+ ),
+ );
+ await tester.tap(find.byKey(const ValueKey('session-filter:needsInput')));
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(find.text('Use the shared cache?'), findsOneWidget);
+ expect(find.text(_paused.name), findsNothing);
+ await tester.tap(
+ find.byKey(ValueKey('session-answer:${agentDestinationId('m', 'a0')}')),
+ );
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(find.byType(HarnessSessionManager), findsNothing);
+ expect(app.focusedPane?.agentId, 'a0');
+ expect(app.panes, hasLength(1));
+ expect(connection.stops, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'an outdated question cannot open work and live closure clears the filter',
+ (tester) async {
+ app.machineStates['m']!.blockedAgents['a0'] = question('a0');
+ await open(tester);
+ await tester.tap(find.byKey(const ValueKey('session-filter:needsInput')));
+ await tester.pumpAndSettle();
+ final answer = tester
+ .widget<Semantics>(
+ find.byKey(
+ ValueKey('session-open:${agentDestinationId('m', 'a0')}'),
+ ),
+ )
+ .properties
+ .onTap!;
+ app.machineStates['m']!.blockedAgents['a0'] = question(
+ 'a0',
+ request: 'replacement',
+ );
+ answer();
+ await tester.pump();
+ expect(app.panes, isEmpty);
+ app.machineStates['m']!.blockedAgents.clear();
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(find.text('No harnesses need your input'), findsOneWidget);
+ expect(find.text('Try another search or filter.'), findsNothing);
+ },
+ );
+
+ test('Genie geometry preserves endpoints and curves a narrowing neck without folding', () {
+ const size = Size(800, 600), target = Offset(740, -20);
+ expect(
+ paneMinimizeSlice(size, target, 0, 0),
+ const Rect.fromLTWH(0, 0, 800, 0),
+ );
+ expect(
+ paneMinimizeSlice(size, target, 0, 1),
+ const Rect.fromLTWH(0, 600, 800, 0),
+ );
+ expect(
+ paneMinimizeSlice(size, target, 1, 0).topLeft,
+ target - const Offset(11, 11),
+ );
+ expect(
+ paneMinimizeSlice(size, target, 1, 1).bottomRight,
+ target + const Offset(11, 11),
+ );
+ final neck = paneMinimizeSlice(size, target, .45, 0);
+ final base = paneMinimizeSlice(size, target, .45, 1);
+ expect(neck.width, lessThan(base.width * .7));
+ for (var frame = 0; frame <= 60; frame++) {
+ double previous = -double.infinity;
+ for (var band = 0; band <= 48; band++) {
+ final slice = paneMinimizeSlice(size, target, frame / 60, band / 48);
+ expect(slice.top, greaterThanOrEqualTo(previous));
+ expect(slice.width, inInclusiveRange(22, 800));
+ previous = slice.top;
+ }
+ }
+ });
+
+ test('inventory deduplicates views, searches context, and sorts deterministically', () async {
+ await app.addAgentToSwarm('m', 'a0');
+ app.newSwarm(name: 'Second view');
+ await app.addAgentToSwarm('m', 'a0');
+ final rows = harnessSessions(app);
+ expect(rows, hasLength(2));
+ expect(rows.first.open, isTrue);
+ expect(
+ visibleHarnessSessions(rows, query: 'office file-menu').single.agent.id,
+ 'a0',
+ );
+ expect(
+ visibleHarnessSessions(
+ rows,
+ filter: SessionFilter.paused,
+ ).single.agent.id,
+ 'saved',
+ );
+ expect(
+ visibleHarnessSessions(
+ rows,
+ filter: SessionFilter.running,
+ ).single.agent.id,
+ 'a0',
+ );
+ expect(
+ visibleHarnessSessions(rows, recent: [rows.last.id]).first.agent.id,
+ 'saved',
+ );
+ expect(
+ visibleHarnessSessions(rows, sort: SessionSort.project).first.agent.id,
+ 'a0',
+ );
+ app.machineStates['m']!.nodeOnline = false;
+ expect(
+ harnessSessions(app)
+ .every((row) => !row.canControl && row.status == 'Offline'),
+ isTrue,
+ );
+ expect(
+ visibleHarnessSessions(
+ harnessSessions(app),
+ filter: SessionFilter.running,
+ ),
+ isEmpty,
+ );
+ });
+
+ testWidgets(
+ 'search, filters, sort, and Escape work in the titlebar popover',
+ (tester) async {
+ await open(tester);
+ expect(find.byType(HarnessSessionManager), findsOneWidget);
+ expect(find.text('Harnesses'), findsOneWidget);
+ expect(find.text('Running 1'), findsOneWidget);
+ expect(find.text('Paused 1'), findsOneWidget);
+ expect(find.text('Ready'), findsNothing);
+ expect(find.text('Paused'), findsNothing);
+ expect(find.textContaining('Pause keeps'), findsNothing);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('session-search')))
+ .decoration
+ ?.hintText,
+ 'Search harnesses, machines, projects, branches…',
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('session-search')),
+ 'office file-menu',
+ );
+ await tester.pumpAndSettle();
+ expect(find.text(_running.name), findsOneWidget);
+ expect(find.text(_paused.name), findsNothing);
+ await tester.tap(find.byTooltip('Clear search'));
+ await tester.tap(find.byKey(const ValueKey('session-filter:paused')));
+ await tester.pumpAndSettle();
+ expect(find.text(_paused.name), findsOneWidget);
+ expect(find.text(_running.name), findsNothing);
+ await tester.tap(find.byTooltip('Sort harnesses'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Project').last);
+ await tester.pumpAndSettle();
+ expect(find.text('Project'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessSessionManager), findsNothing);
+ expect(connection.stops, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'pause sends one stop, retains saved session, then resume sends one durable request',
+ (tester) async {
+ await open(tester);
+ connection.inventory = Completer<Map<String, dynamic>>();
+ await tester.tap(toggle('a0'));
+ await tester.pump();
+ expect(connection.stops, ['a0']);
+ expect(find.byTooltip('Pausing…'), findsOneWidget);
+ expect(toggle('a0'), findsNothing);
+ connection.stopReplies.single.complete({'deleted': true});
+ await tester.pump();
+ expect(
+ find.text(_running.name),
+ findsOneWidget,
+ reason: 'The row stays visible while the saved inventory loads',
+ );
+ connection.inventory!.complete({
+ 'agents': [
+ {
+ 'id': 'a0',
+ 'name': _running.name,
+ 'engine': 'claude',
+ 'sessionId': 'conversation',
+ 'status': 'stopped',
+ 'terminal': {'available': false},
+ },
+ {
+ 'id': 'saved',
+ 'name': _paused.name,
+ 'engine': 'codex',
+ 'sessionId': 'saved-conversation',
+ 'status': 'stopped',
+ },
+ ],
+ });
+ await tester.pumpAndSettle();
+ expect(app.stateOf('m')!.agents.first.isStopped, isTrue);
+ expect(find.text('Running 0'), findsOneWidget);
+ expect(find.text('Paused 2'), findsOneWidget);
+ await tester.tap(toggle('a0'));
+ await tester.pump();
+ expect(connection.types, ['agent_resume']);
+ expect(find.byTooltip('Resuming…'), findsOneWidget);
+ connection.restartReplies.single.complete(
+ restartReceipt(
+ connection.requests.single['creationId'] as String,
+ name: _running.name,
+ sessionId: 'conversation',
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,
+ isFalse,
+ );
+ expect(
+ app.allPanes,
+ isEmpty,
+ reason: 'Resuming in the manager does not force open a pane',
+ );
+ },
+ );
+
+ testWidgets('pause failure is inline and leaves the session running', (
+ tester,
+ ) async {
+ connection.inventory = Completer<Map<String, dynamic>>()
+ ..complete({
+ 'agents': [
+ {
+ 'id': 'a0',
+ 'name': _running.name,
+ 'engine': 'claude',
+ 'sessionId': 'conversation',
+ 'terminal': {'available': true},
+ },
+ ],
+ });
+ await open(tester);
+ await tester.tap(toggle('a0'));
+ await tester.pump();
+ connection.stopReplies.single.complete({
+ 'error': 'REFUSED',
+ 'detail': 'Machine busy. Try again.',
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Pause failed: Machine busy. Try again.'), findsOneWidget);
+ expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
+ expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNotNull);
+ });
+
+ testWidgets(
+ 'closing and reopening the manager cannot duplicate an in-flight pause',
+ (tester) async {
+ connection.inventory = Completer<Map<String, dynamic>>();
+ await open(tester);
+ await tester.tap(toggle('a0'));
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ connection.stopReplies.single.complete({'deleted': true});
+ await tester.pump();
+ await tester.tap(find.byTooltip('Harnesses'));
+ await tester.pump();
+ expect(toggle('a0'), findsNothing);
+ expect(find.byTooltip('Pausing…'), findsOneWidget);
+ expect(connection.stops, ['a0']);
+ connection.inventory!.completeError(StateError('refresh failed'));
+ await tester.pumpAndSettle();
+ expect(find.text(_running.name), findsOneWidget);
+ expect(find.text('Paused 2'), findsOneWidget);
+ expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNotNull);
+ expect(connection.stops, ['a0']);
+ },
+ );
+
+ testWidgets(
+ 'unsupported engines stay openable without a misleading pause control',
+ (tester) async {
+ app
+ .stateOf('m')!
+ .agents
+ .add(
+ const Agent(
+ id: 'unsupported',
+ name: 'Other engine',
+ engine: 'opencode',
+ sessionId: 'history',
+ terminalAvailable: true,
+ ),
+ );
+ await open(tester);
+ expect(
+ tester.widget<IconButton>(toggle('unsupported')).onPressed,
+ isNull,
+ );
+ expect(
+ find.byTooltip(
+ 'Pause and resume are not available for this engine yet.',
+ ),
+ findsOneWidget,
+ );
+ expect(connection.stops, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'a resuming harness can open for native login or permission review',
+ (tester) async {
+ app.adoptSessionForTest(terminal('saved', []));
+ await open(tester);
+ await tester.tap(toggle('saved'));
+ await tester.pump();
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'saved',
+ 'name': _paused.name,
+ 'engine': 'codex',
+ 'sessionId': 'saved-conversation',
+ 'terminal': {'available': true},
+ 'launch': {'state': 'starting'},
+ },
+ },
+ });
+ await tester.pump();
+ expect(toggle('saved'), findsNothing);
+ await tester.tap(
+ find.byKey(
+ ValueKey('session-open:${agentDestinationId('m', 'saved')}'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessSessionManager), findsNothing);
+ expect(app.focusedPane?.agentId, 'saved');
+ expect(connection.types, ['agent_resume']);
+ connection.restartReplies.single.complete(
+ restartReceipt(
+ connection.requests.single['creationId'] as String,
+ agentId: 'saved',
+ sessionId: 'saved-conversation',
+ ),
+ );
+ await tester.pumpAndSettle();
+ },
+ );
+
+ testWidgets('VoiceOver exposes opening and pausing as separate actions', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ await open(tester);
+ final node = tester.getSemantics(
+ find.byKey(ValueKey('session-open:${agentDestinationId('m', 'a0')}')),
+ );
+ expect(node.label, 'Open Font styling review');
+ expect(node.value, contains('iMac — Office'));
+ expect(node.getSemanticsData().hasAction(SemanticsAction.tap), isTrue);
+ semantics.dispose();
+ });
+
+ testWidgets(
+ 'uncertain resume checks its existing receipt instead of relaunching',
+ (tester) async {
+ await open(tester);
+ await tester.tap(toggle('saved'));
+ await tester.pump();
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_resume'),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('Still waiting for the resume response'),
+ findsOneWidget,
+ );
+ await tester.tap(toggle('saved'));
+ await tester.pump();
+ expect(connection.requests, hasLength(1));
+ expect(
+ connection.checks.single['creationId'],
+ connection.requests.single['creationId'],
+ );
+ connection.checkReplies.single.complete(
+ restartReceipt(
+ connection.requests.single['creationId'] as String,
+ agentId: 'saved',
+ sessionId: 'saved-conversation',
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('Still waiting for the resume response'),
+ findsNothing,
+ );
+ },
+ );
+
+ testWidgets('keyboard search opens its first matching session', (
+ tester,
+ ) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await open(tester);
+ await tester.enterText(
+ find.byKey(const ValueKey('session-search')),
+ 'file-menu',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.focusedPane?.agentId, 'a0');
+ expect(find.byType(HarnessSessionManager), findsNothing);
+ });
+
+ testWidgets(
+ 'reduced motion closes immediately and keeps the saved inventory',
+ (tester) async {
+ await app.addAgentToSwarm('m', 'a0');
+ await mount(tester, app);
+ tester.platformDispatcher.accessibilityFeaturesTestValue =
+ const FakeAccessibilityFeatures(disableAnimations: true);
+ addTearDown(
+ tester.platformDispatcher.clearAccessibilityFeaturesTestValue,
+ );
+ await tester.pump();
+ final scope = tester.widget<PaneMinimizeScope>(
+ find.byType(PaneMinimizeScope),
+ );
+ await scope.close(app.focusedPane!);
+ await tester.pumpAndSettle();
+ expect(app.panes, isEmpty);
+ expect(scope.controller.paneId, isNull);
+ expect(connection.stops, isEmpty);
+ },
+ );
+
+ testWidgets('offline and shared rows cannot send lifecycle commands', (
+ tester,
+ ) async {
+ app.machineStates['m']!.nodeOnline = false;
+ await open(tester);
+ expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNull);
+ expect(tester.widget<IconButton>(toggle('saved')).onPressed, isNull);
+ expect(find.text('Offline'), findsNWidgets(2));
+ expect(connection.requests, isEmpty);
+ expect(connection.stops, isEmpty);
+ app.machineStates['m']!
+ ..nodeOnline = true
+ ..machine = const Machine(
+ machineId: 'm',
+ name: 'Shared Mac',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ );
+ app.machineStates['m']!.connectionStatus = ConnectionStatus.disconnected;
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNull);
+ expect(find.text('View only'), findsNWidgets(2));
+ });
+
+ testWidgets(
+ 'opening a row reveals its existing pane and restores terminal focus',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await app.addAgentToSwarm('m', 'a0');
+ final original = app.focusedPane!;
+ app.newSwarm(name: 'Another tab');
+ await open(tester);
+ await tester.tap(find.text(_running.name));
+ await tester.pumpAndSettle();
+ expect(app.allPanes, [original]);
+ expect(app.focusedPane, original);
+ expect(find.byType(HarnessSessionManager), findsNothing);
+ expect(connection.requests, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'closing a pane animates into the manager without stopping its process',
+ (tester) async {
+ final renderDir = Platform.environment['SESSION_MANAGER_RENDER_DIR'];
+ if (renderDir != null) await tester.runAsync(loadPreviewFonts);
+ final live = terminal('a0', [])..agentName = 'Font styling review';
+ live.terminal.write('Reviewing typography and spacing.\r\n\r\n');
+ for (var i = 0; i < 20; i++) {
+ live.terminal.write(
+ ' ${i + 1} Checking pane labels and native controls\r\n',
+ );
+ }
+ app.adoptSessionForTest(live);
+ await app.addAgentToSwarm('m', 'a0');
+ final pane = app.focusedPane!;
+ final sibling = app.adoptSessionForTest(terminal('sibling', []));
+ await mount(tester, app);
+ final scope = tester.widget<PaneMinimizeScope>(
+ find.byType(PaneMinimizeScope),
+ );
+ Future<void> frame(String name) async {
+ if (renderDir != null) {
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(Uri.file('$renderDir/minimize-$name.png')),
+ );
+ }
+ }
+
+ await frame('start');
+ final closing = scope.close(pane);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 160));
+ expect(app.panes, [sibling]);
+ expect(find.byKey(pane.cellKey), findsNothing);
+ expect(scope.controller.animation.value, greaterThan(0));
+ expect(
+ scope.controller.snapshot,
+ isNotNull,
+ reason: "The native snapshot drives the curved motion",
+ );
+ expect(find.byType(PaneMinimizeSnapshot), findsOneWidget);
+ await frame('neck');
+ await tester.pump(const Duration(milliseconds: 140));
+ await frame('travel');
+ await tester.pump(const Duration(milliseconds: 100));
+ await frame('arrival');
+ await tester.pump(const Duration(milliseconds: 160));
+ await closing;
+ await tester.pumpAndSettle();
+ expect(app.panes, [sibling]);
+ expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
+ expect(connection.stops, isEmpty);
+ await tester.tap(find.byTooltip('Harnesses'));
+ await tester.pumpAndSettle();
+ expect(find.text(_running.name), findsOneWidget);
+ },
+ );
+
+ testWidgets('native titlebar opens and toggles the same manager', (
+ tester,
+ ) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ final updates = <Map>[];
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
+ call,
+ ) async {
+ if (call.method == 'update') updates.add(call.arguments as Map);
+ return null;
+ });
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ null,
+ ),
+ );
+ await mount(tester, app, nativeTabs: true);
+ void nativeClick() =>
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('sessions'),
+ ),
+ (_) {},
+ );
+ nativeClick();
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessSessionManager), findsOneWidget);
+ expect(updates.last['sessionsOpen'], isTrue);
+ expect(updates.last['runningSessions'], 1);
+ nativeClick();
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessSessionManager), findsNothing);
+ expect(updates.last['sessionsOpen'], isFalse);
+ app.machineStates['m']!.blockedAgents['a0'] = question('a0');
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(updates.last['attention'], 1);
+ app.machineStates['m']!.blockedAgents.clear();
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(updates.last['attention'], 0);
+ });
+
+ testWidgets('session manager fits the minimum Mac window and scaled text', (
+ tester,
+ ) async {
+ await open(tester);
+ tester.view.physicalSize = const Size(880, 560);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ final rect = tester.getRect(find.byType(HarnessSessionManager));
+ expect(rect.right, lessThanOrEqualTo(880));
+ expect(rect.bottom, lessThanOrEqualTo(560));
+ tester.platformDispatcher.textScaleFactorTestValue = 1.5;
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ });
+
+ final renderDir = Platform.environment['SESSION_MANAGER_RENDER_DIR'];
+ testWidgets(
+ 'render session manager for visual review',
+ skip: renderDir == null,
+ (tester) async {
+ await tester.runAsync(loadPreviewFonts);
+ debugDisableShadows = false;
+ addTearDown(() => debugDisableShadows = true);
+ app.machineStates['m']!.agents.addAll([
+ const Agent(
+ id: 'review',
+ name: 'File menu ordering',
+ engine: 'codex',
+ sessionId: 'review-history',
+ terminalAvailable: true,
+ project: _project,
+ ),
+ const Agent(
+ id: 'api',
+ name: 'API response caching',
+ engine: 'opencode',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'backend',
+ cwd: '/work/backend',
+ branch: 'perf/cache',
+ ),
+ ),
+ const Agent(
+ id: 'docs',
+ name: 'Getting started guide',
+ engine: 'claude',
+ sessionId: 'docs-history',
+ status: 'stopped',
+ project: AgentProject(
+ name: 'docs',
+ cwd: '/work/docs',
+ branch: 'main',
+ ),
+ ),
+ ]);
+ final now = DateTime.now();
+ final ages = {
+ 'a0': 5,
+ 'saved': 1440,
+ 'review': 12,
+ 'api': 60,
+ 'docs': 2880,
+ };
+ app.machineStates['m']!.agents = [
+ for (final agent in app.machineStates['m']!.agents)
+ Agent.fromJson({
+ 'id': agent.id,
+ 'name': agent.name,
+ 'engine': agent.engine,
+ 'sessionId': agent.sessionId,
+ 'status': agent.status,
+ 'terminal': {'available': agent.terminalAvailable},
+ 'project': {
+ 'name': agent.project?.name,
+ 'cwd': agent.project?.cwd,
+ 'branch': agent.project?.branch,
+ },
+ 'updatedAt': now
+ .subtract(Duration(minutes: ages[agent.id]!))
+ .toIso8601String(),
+ }),
+ ];
+ app.machineStates['m']!.blockedAgents['api'] = question('api');
+ app.machineStates['m']!.processingAgentIds.add('a0');
+ app.renameSwarm(app.activeSwarmId, _running.name);
+ app.adoptSessionForTest(terminal('a0', [])..agentName = _running.name);
+ await app.addAgentToSwarm('m', 'a0');
+ await open(tester);
+ final root = tester.widget<MaterialApp>(find.byType(MaterialApp));
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: root.theme,
+ home: root.home,
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.runAsync(() async {
+ await Future.wait(
+ find
+ .byType(Image)
+ .evaluate()
+ .map(
+ (element) =>
+ precacheImage((element.widget as Image).image, element),
+ ),
+ );
+ });
+ await tester.pumpAndSettle();
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(Uri.file('$renderDir/sessions.png')),
+ );
+ await tester.tap(find.byKey(const ValueKey('session-filter:needsInput')));
+ await tester.pumpAndSettle();
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(Uri.file('$renderDir/needs-input.png')),
+ );
+ debugDisableShadows = true;
+ },
+ );
+}
diff --git a/desktop/test/remote_terminal_handoff_test.dart b/desktop/test/remote_terminal_handoff_test.dart
index 4a3a62821..eb76a1e3a 100644
--- a/desktop/test/remote_terminal_handoff_test.dart
+++ b/desktop/test/remote_terminal_handoff_test.dart
@@ -31,7 +31,8 @@ class _Connection extends WsConn {
Duration timeout = const Duration(seconds: 20),
}) {
calls.add((type, Map.of(payload)));
- return answer?.call(type, payload) ?? Future.value({});
+ return answer?.call(type, payload) ??
+ Future.value(type == 'agent_delete' ? {'deleted': true} : {});
}
}
diff --git a/desktop/test/swarm_attention_picker_test.dart b/desktop/test/swarm_attention_picker_test.dart
index dd74f1286..c3cf58c56 100644
--- a/desktop/test/swarm_attention_picker_test.dart
+++ b/desktop/test/swarm_attention_picker_test.dart
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/widgets/swarm_attention.dart';
+import 'package:harness/widgets/harness_session_manager.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'swarm_attention_test.dart' show waitingQuestion, announceQuestion;
@@ -11,10 +12,13 @@ import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
import 'swarm_switcher_test.dart' show selectedRow;
-Finder get attentionField => find.byWidgetPredicate(
- (w) =>
- w is TextField &&
- w.decoration?.hintText == 'Find a question, agent, or project',
+Finder get attentionField => find.byKey(const ValueKey('session-search'));
+Finder get selectedHarness => find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics &&
+ widget.properties.selected == true &&
+ widget.key is ValueKey<String> &&
+ (widget.key! as ValueKey<String>).value.startsWith('session-open:'),
);
void main() {
@@ -93,15 +97,10 @@ void main() {
tester.widget<TextField>(attentionField).focusNode!.hasFocus,
isTrue,
);
- expect(
- (ModalRoute.of(
- tester.element(attentionField),
- ) as TransitionRoute).transitionDuration,
- Duration.zero,
- );
expect(find.byType(BackdropFilter), findsNothing);
+ expect(find.byType(Dialog), findsNothing);
await chord(tester, LogicalKeyboardKey.keyI, shift: true);
- expect(find.byType(Dialog), findsOneWidget);
+ expect(find.byType(HarnessSessionManager), findsOneWidget);
await tester.enterText(attentionField, 'region host');
await tester.pump();
expect(find.text('Choose the deployment region'), findsOneWidget);
@@ -147,49 +146,54 @@ void main() {
}
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyI, shift: true);
- expect(find.byType(ListTile).evaluate().length, lessThan(25));
- for (var i = 0; i < 12; i++) {
+ expect(
+ find
+ .byType(Semantics)
+ .evaluate()
+ .where(
+ (e) => (e.widget.key?.toString() ?? '').contains('session-open:'),
+ )
+ .length,
+ lessThan(25),
+ );
+ for (var i = 0; i < 13; i++) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
- expect(selectedRow, findsOneWidget);
- final row = tester.getRect(selectedRow);
+ expect(selectedHarness, findsOneWidget);
+ final row = tester.getRect(selectedHarness);
final list = tester.getRect(find.byType(ListView));
expect(row.top, greaterThanOrEqualTo(list.top));
expect(row.bottom, lessThanOrEqualTo(list.bottom));
}
await tester.pump();
- final selection = tester.widget<ListTile>(selectedRow).key;
- expect(selection, ValueKey(agentDestinationId('m', 'a12')));
+ final selection = tester.widget<Semantics>(selectedHarness).key;
+ expect(
+ selection,
+ ValueKey('session-open:${agentDestinationId('m', 'a12')}'),
+ );
final list = tester.getRect(find.byType(ListView));
- final row = tester.getRect(selectedRow);
+ final row = tester.getRect(selectedHarness);
expect(row.top, greaterThanOrEqualTo(list.top));
expect(row.bottom, lessThanOrEqualTo(list.bottom));
machine.blockedAgents['a30'] = waitingQuestion('a30', ageOrder: -1);
app.dismissError();
await tester.pump();
await tester.pump();
- expect(tester.widget<ListTile>(selectedRow).key, selection);
- await tester.sendKeyDownEvent(LogicalKeyboardKey.control);
- await tester.sendKeyEvent(LogicalKeyboardKey.keyN);
- await tester.sendKeyUpEvent(LogicalKeyboardKey.control);
+ expect(tester.widget<Semantics>(selectedHarness).key, selection);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(
- tester.widget<ListTile>(selectedRow).key,
- ValueKey(agentDestinationId('m', 'a13')),
+ tester.widget<Semantics>(selectedHarness).key,
+ ValueKey('session-open:${agentDestinationId('m', 'a13')}'),
);
- await tester.sendKeyDownEvent(LogicalKeyboardKey.control);
- await tester.sendKeyEvent(LogicalKeyboardKey.keyP);
- await tester.sendKeyUpEvent(LogicalKeyboardKey.control);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
- expect(tester.widget<ListTile>(selectedRow).key, selection);
+ expect(tester.widget<Semantics>(selectedHarness).key, selection);
machine.blockedAgents.remove('a12');
app.dismissError();
await tester.pump();
expect(find.text('Question 12?'), findsNothing);
- expect(
- tester.widget<ListTile>(selectedRow).key,
- ValueKey(agentDestinationId('m', 'a13')),
- );
+ expect(selectedHarness, findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(attentionField, findsNothing);
@@ -208,23 +212,27 @@ void main() {
machine.blockedAgents['missing'] = waitingQuestion('missing');
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyI, shift: true);
- expect(find.text('Unavailable'), findsOneWidget);
- expect(tester.widget<ListTile>(selectedRow).enabled, isFalse);
+ expect(find.text('Offline'), findsOneWidget);
+ final unavailable = find.byKey(
+ ValueKey('session-open:${agentDestinationId('m', 'missing')}'),
+ );
+ expect(tester.widget<Semantics>(unavailable).properties.enabled, isFalse);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(attentionField, findsOneWidget);
expect(app.panes, isEmpty);
await tester.enterText(attentionField, 'not found');
await tester.pump();
- expect(find.text('No matching questions'), findsOneWidget);
+ expect(find.text('No matching harnesses'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(attentionField, findsOneWidget);
+ await tester.enterText(attentionField, '');
machine.blockedAgents.clear();
app.dismissError();
await tester.pump();
- expect(find.text('No agents need your input'), findsOneWidget);
- await tester.tap(find.byTooltip('Close notifications'));
+ expect(find.text('No harnesses need your input'), findsOneWidget);
+ await tester.tap(find.byTooltip('Close harnesses'));
await tester.pump();
expect(app.panes, isEmpty);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/swarm_immediate_input_test.dart b/desktop/test/swarm_immediate_input_test.dart
index dcdafb52c..e28de558c 100644
--- a/desktop/test/swarm_immediate_input_test.dart
+++ b/desktop/test/swarm_immediate_input_test.dart
@@ -34,6 +34,7 @@ void main() {
'waiting composer',
'tab',
'close pane',
+ if (nativeEntry) 'close pane menu',
'close tab',
'new tab',
]) {
@@ -86,11 +87,14 @@ void main() {
LogicalKeyboardKey.arrowLeft,
),
'tab' => ('swarm.select_1', LogicalKeyboardKey.digit1),
- 'close pane' => ('pane.close', LogicalKeyboardKey.keyW),
+ 'close pane' ||
+ 'close pane menu' => ('pane.close', LogicalKeyboardKey.keyW),
'close tab' => ('swarm.close', LogicalKeyboardKey.keyW),
_ => ('swarm.new', LogicalKeyboardKey.keyT),
};
- if (nativeEntry) {
+ if (action == 'close pane menu') {
+ await native(tester, 'closePane');
+ } else if (nativeEntry) {
await native(tester, 'keymapCommand', {'command': commandId});
} else {
await command(tester, key, shift: action == 'close pane');
diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dart
index a081d3f2c..ca965f59f 100644
--- a/desktop/test/swarm_interactions_test.dart
+++ b/desktop/test/swarm_interactions_test.dart
@@ -21,6 +21,7 @@ import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/codex_profile_field.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
import 'package:harness/widgets/pane_header_actions.dart';
+import 'package:harness/widgets/harness_session_manager.dart';
import 'package:harness/widgets/swarm_dialogs.dart';
import 'package:harness/widgets/terminal_find_bar.dart';
@@ -505,15 +506,18 @@ void main() {
expect(updates.last['canReopen'], isFalse);
final attention = native('notifications');
await tester.pump();
- expect(find.text('Needs input'), findsOneWidget);
- expect(updates.last['enabled'], isFalse);
- await native('new');
- await native('notifications');
+ expect(find.byType(HarnessSessionManager), findsOneWidget);
+ expect(updates.last['sessionsOpen'], isTrue);
+ expect(updates.last['enabled'], isTrue);
+ final repeatedAttention = native('notifications');
+ await tester.pump();
+ await repeatedAttention;
expect(app.swarms.single.name, 'Recover me');
- expect(find.byType(Dialog), findsOneWidget);
+ expect(find.byType(HarnessSessionManager), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
await attention;
+ expect(updates.last['sessionsOpen'], isFalse);
expect(updates.last['enabled'], isTrue);
expect(updates.last['canFind'], isFalse);
app.machineStates['m']!.nodeOnline = true;
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index e37e19319..927035c51 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -760,7 +760,7 @@ void main() {
);
testWidgets(
- 'notifications show only current questions and navigate to their originating swarm',
+ 'attention shortcut opens current questions in Harnesses and their originating swarm',
(tester) async {
final app = createApp();
await app.addAgentToSwarm('m', 'a0');
@@ -793,7 +793,7 @@ void main() {
});
await chord(tester, LogicalKeyboardKey.keyI, shift: true);
await tester.pump(const Duration(milliseconds: 300));
- expect(find.text('No agents need your input'), findsOneWidget);
+ expect(find.text('No harnesses need your input'), findsOneWidget);
await tester.pumpWidget(const SizedBox());
app.dispose();
},
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index f4a75276c..eb2fbb187 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -143,10 +143,9 @@ private extension SwarmTabStrip {
}
func checkStartupPalette(_ expected: SwarmNativePalette) throws {
- try checkTitlebar(palette == expected && newButton.contentTintColor == expected.accent && notificationButton.contentTintColor == expected.accent &&
- newButton.contentTintColor == expected.accent,
+ try checkTitlebar(palette == expected && newButton.contentTintColor == expected.accent && sessionsButton.contentTintColor == expected.accent,
"Initial search and new-swarm colors use the saved palette")
- try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !notificationButton.isEnabled,
+ try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !sessionsButton.isEnabled,
"Initial palette setup does not create or enable workspace controls")
}
@@ -262,27 +261,48 @@ private extension SwarmTabStrip {
update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0"))
try checkTitlebar(newButton.toolTip == "New Tab ⌘T" && storeButton.toolTip == "Harness Store ⌘S",
"Titlebar actions expose their keyboard alternatives")
- try checkTitlebar(notificationButton.frame.maxX <= scroll.frame.minX,
- "The bell is before the tabs beside the traffic lights")
+ try checkTitlebar(scroll.frame.minX == 0,
+ "The tabs start beside the traffic lights without a separate bell")
try checkTitlebar(scroll.frame.maxX <= newButton.frame.minX && newButton.frame.maxX <= storeButton.frame.minX,
"New Tab follows the tabs while the Store stays on the right")
try checkTitlebar(storeButton.title == "Harness Store" && storeButton.accessibilityLabel() == "Harness Store",
"The Store action has a visible and accessible name")
+ try checkTitlebar(newButton.frame.maxX < sessionsButton.frame.minX && sessionsButton.frame.maxX < storeButton.frame.minX && storeButton.frame.maxX <= bounds.width,
+ "Harnesses sits to the left of the Store without overlapping its hit target")
+ try checkTitlebar(sessionsButton.accessibilityLabel() == "Harnesses", "Harnesses has an accessible name")
try checkTitlebar(!subviews.contains(where: { $0 is NSTextField }), "The titlebar has no competing text editor")
events.removeAll()
newButton.performClick(nil)
- notificationButton.performClick(nil)
+ sessionsButton.performClick(nil)
storeButton.performClick(nil)
- try checkTitlebar(events == ["new", "notifications", "store"],
- "The tab, notification and Store buttons dispatch once")
- try checkTitlebar(notificationButton.hasAttention, "The bell represents pending agent attention")
+ try checkTitlebar(events == ["new", "sessions", "store"],
+ "The tab, Harnesses and Store buttons dispatch once")
+ try checkTitlebar(sessionsButton.attention > 0 && sessionsButton.toolTip?.contains("input") == true, "Harnesses represents pending agent attention")
+ let originalAttention = sessionsButton.attention
+ sessionsButton.attention = 0
+ let quietPixels = sessionsButton.renderedPixels()
+ try checkTitlebar(sessionsButton.attentionLabel == nil,
+ "Running harnesses without questions have no notification badge")
+ for count in [1, 6, 42, 100] {
+ sessionsButton.attention = count
+ let label = sessionsButton.attentionLabel!
+ let width = (label as NSString).size(withAttributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 9, weight: .semibold)]).width
+ let badge = sessionsButton.badgeFrame(textWidth: width)
+ try checkTitlebar(sessionsButton.bounds.contains(badge) && badge.maxX == sessionsButton.bounds.maxX &&
+ (sessionsButton.isFlipped ? badge.minY == sessionsButton.bounds.minY : badge.maxY == sessionsButton.bounds.maxY),
+ "The attention badge stays in the top-right corner and fits at count \(count)")
+ try checkTitlebar(sessionsButton.renderedPixels() != quietPixels,
+ "Pending questions visibly add a count badge at \(count)")
+ }
+ try checkTitlebar(sessionsButton.attentionLabel == "99+", "Large attention counts stay compact")
+ sessionsButton.attention = originalAttention
let oldButton = newButton
var themedState = state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0")
themedState["palette"] = ["workspace": Int64(0xff252d43), "search": Int64(0xff262f46)]
update(themedState)
try checkTitlebar(newButton === oldButton && tabs[0] === original,
"Palette changes retain native control identity")
- try checkTitlebar(newButton.contentTintColor == palette.accent && notificationButton.contentTintColor == palette.accent,
+ try checkTitlebar(newButton.contentTintColor == palette.accent && sessionsButton.contentTintColor == palette.accent,
"Both toolbar icons receive the coordinated palette")
events.removeAll()
try original.checkEnabled(true)
@@ -293,12 +313,12 @@ private extension SwarmTabStrip {
events.removeAll()
update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0", enabled: false))
try original.checkEnabled(false)
- try checkTitlebar(!newButton.isEnabled && !notificationButton.isEnabled && !storeButton.isEnabled, "Titlebar actions disable with a modal")
+ try checkTitlebar(!newButton.isEnabled && !sessionsButton.isEnabled && !storeButton.isEnabled, "Titlebar actions disable with a modal")
try checkTitlebar(actionPixels != storeButton.renderedPixels(),
"The Store visibly dims when a workspace modal disables it")
original.clickBothActions()
newButton.performClick(nil)
- notificationButton.performClick(nil)
+ sessionsButton.performClick(nil)
storeButton.performClick(nil)
try checkTitlebar(events.isEmpty, "Disabled controls emit no actions")
try checkDragOperations()
@@ -372,7 +392,7 @@ private extension SwarmTabStrip {
messenger.finishNextReply()
try checkTitlebar(window.firstResponder === window.contentInput,
"The latest acknowledged tab action restores content focus")
- for (button, method) in [(notificationButton, "notifications")] {
+ for (button, method) in [(sessionsButton, "sessions")] {
window.makeFirstResponder(button)
let before = messenger.calls.count
button.performClick(nil)
@@ -382,7 +402,7 @@ private extension SwarmTabStrip {
"The toolbar waits for Flutter's destination focus tree")
messenger.finishNextReply()
try checkTitlebar(window.firstResponder === window.contentInput,
- "Notification control returns keyboard ownership to Flutter")
+ "Harnesses returns keyboard ownership to Flutter")
}
messenger.holdReplies = false
}
@@ -877,7 +897,7 @@ private extension SwarmTitlebar {
let attention = menu.items.first(where: { $0.representedObject as? String == "notifications" }) else {
throw TitlebarCheckFailure(message: "View menu exposes agents needing input")
}
- try checkTitlebar(attention.title == "Agents Needing Input…", "Native command names its destination")
+ try checkTitlebar(attention.title == "Harnesses Needing Input…", "Native command names its destination")
try checkTitlebar(attention.keyEquivalent == "i" && attention.keyEquivalentModifierMask == [.command, .shift], "Native attention shortcut matches Flutter")
try checkTitlebar(attention.target === self && attention.action == #selector(menuAction(_:)), "Native attention command uses the guarded channel handler")
actionsEnabled = false
@@ -1144,7 +1164,7 @@ do {
try checkTitlebar(swarmRow.menuTitle().string == "My swarm", "Empty swarm rows have no invented machine label")
let sharedSwarm = SwarmHistoryEntry(["id": "shared", "title": "Workshop", "swarm": true, "machineName": "2 machines"])!
try checkTitlebar(sharedSwarm.menuTitle().string == "Workshop\t2 machines", "Swarm machine counts use the same trailing column as agent machines")
- for button in [SwarmIconButton(), SwarmNotificationButton(), SwarmCloseButton()] {
+ for button in [SwarmIconButton(), SwarmSessionsButton(), SwarmCloseButton()] {
button.frame = NSRect(x: 0, y: 0, width: 28, height: 28)
button.image = NSImage(systemSymbolName: "plus", accessibilityDescription: nil)
button.isBordered = false