The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep Super Tab agents alive when their terminals are hidden (#1408)
Deed3f990ce5776
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 04180b33f..48d5c8859 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -470,6 +470,18 @@ describe('Super Tabs on a real Mongo replica set', () => {expect((await store.hostTabs(host, 'test-host')).find(t => t.tabId === tab)?.observers).not.toContainEqual({ email: peer.email, userId: peer.sub })})+ it('marks members of only archived groups inactive for host retention', async () => {+ const { tab, lead } = await fixture()+ const group = (await run(tab, { type: 'conversation.create', title: 'Done work', brief: '', checks: [] })).result.conversationId as string+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),+ name: 'Builder', configuration: config, lead: false })).result.agentId as string+ const active = async () => Object.fromEntries((await store.hostTabs(host, 'test-host'))+ .filter(t => t.tabId === tab).map(t => [t.agent.id, t.active]))+ expect(await active()).toEqual({ [lead]: true, [worker]: true })+ await run(tab, { type: 'conversation.archive', conversationId: group, archived: true })+ expect(await active()).toEqual({ [lead]: true, [worker]: false })+ })+it('serializes native start claims and fences a restored target-machine grant', async () => {const { tab } = await fixture()const request = { conversationId: 'lead', machineId: 'test-host', engine: 'claude', name: 'Builder', cwd: '/fixture/repo', worktree: true,diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex d6e9b317f..64767b069 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -314,7 +314,9 @@ export class SuperTabStore {for (const target of state.agents.filter(a => a.machineId === machineId && a.machineOwnerId === user.sub)) {try { agent(state, target.id); await this.agentGrant(tx, state, target) }catch (error) { if (error instanceof SuperTabError) continue; throw error }- result.push({ tabId: row.id, revision: row.revision, paused: state.paused, agent: target,+ // `active` lets the host release members that are only in archived groups to automatic cleanup.+ const active = state.conversations.some(c => !c.archived && c.agentIds.includes(target.id))+ result.push({ tabId: row.id, revision: row.revision, paused: state.paused, active, agent: target,observers: people.filter(p => p.id !== user.sub).map(p => ({ email: p.email, userId: p.id })) })}}diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.tsindex f9d96c490..98a7aeb0e 100644--- a/cli/e2e/agentClient.e2e.ts+++ b/cli/e2e/agentClient.e2e.ts@@ -18,6 +18,7 @@ import { afterEach, describe, expect, it, onTestFailed } from 'vitest'import { LocalClient } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'+import { retainedHarnesses } from '../src/superTabs/retention.js'const HARNESS_INSTRUCTIONS = 'You are running in Harness, and the person can watch you. You can hand work to other agents (Claude Code, Codex) that run in their own harnesses: `harness new`, `harness wait`, `harness show`, `harness close` (see `harness --help`). Start one only for work that can run in parallel, needs another model, or takes long; do quick work yourself, and close each one once you have its answer. Only use or close harnesses you started.'const ME: FakeMachine = { machineId: 'b8'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000b8', name: 'studio', token: 'e2e-token-agent-client' }@@ -201,7 +202,7 @@ describe('Harness for agents, end to end', () => {// Owner, October 12: "we need to be very careful about when to start a new agent so we don't waste user token and we// need to properly clean up after too". The cleanup runs in its own process here, as it does by default (the edge// host): what the core tells it and what it asks back cross the link.- const { d } = await signedIn({ agents_start_agents: true })+ const { d, relay } = await signedIn({ agents_start_agents: true })const client = await LocalClient.connect(d, { machineId: ME.machineId })const list = async (includeStopped = false) => (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped }, 30_000)).agentsconst lead = async (name: string) => {@@ -248,6 +249,15 @@ describe('Harness for agents, end to end', () => {const second = await lead('lead2')const joined = await start(second, 'joined')const left = await start(second, 'left')+ const shared = await start(second, 'shared')+ relay.superTabs = async (_method, raw) => {+ const path = new URL(raw, relay.httpUrl).pathname+ return { data: path === `/api/super-tabs/hosts/${ME.machineId}`+ ? [{ tabId: 'retained-team', agent: { id: 'shared-member', harnessId: shared.id, machineId: ME.machineId }, observers: [] }]+ : [] }+ }+ expect(await client.request('super_tabs', { action: 'wake' })).toMatchObject({ ok: true })+ await until('the team host to retain its member', () => retainedHarnesses(d.dataDir).has(shared.id) || null, 10_000, 100)client.send('message', { agentId: joined.id, content: 'hello from the person' })// The app closes lead, as a pane's close does (`agent_close`): kid closes with it.@@ -263,10 +273,12 @@ describe('Harness for agents, end to end', () => {expect(byPerson.code, byPerson.out + byPerson.err).toBe(0)await until('left to close with lead2', async () => (await stateOf(left)) === 'stopped' || null, 60_000, 500)expect(await stateOf(joined)).toBe('active')+ expect(await stateOf(shared)).toBe('active')// One line for each close.expect(d.log()).toMatch(/\[agent-cleanup\] closed kid \(\w+\): the harness that started it was closed\. Its conversation is kept\./)expect(d.log()).toMatch(/\[agent-cleanup\] closed left \(\w+\): the harness that started it was closed\./)expect(d.log()).not.toMatch(/\[agent-cleanup\] closed joined/)+ expect(d.log()).not.toMatch(/\[agent-cleanup\] closed shared/)client.close()})diff --git a/cli/e2e/superTabs.e2e.ts b/cli/e2e/superTabs.e2e.tsindex b325e2595..5dbed7530 100644--- a/cli/e2e/superTabs.e2e.ts+++ b/cli/e2e/superTabs.e2e.ts@@ -7,6 +7,7 @@ import { join } from 'node:path'import { afterEach, expect, it, onTestFailed } from 'vitest'import { superTabCommand } from '../src/superTabs/command.js'import { object } from '../src/superTabs/wire.js'+import { retainedHarnesses } from '../src/superTabs/retention.js'import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'import { LocalClient } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'@@ -256,6 +257,8 @@ it('starts either engine once, posts to its captured group and delivers shared iconst listed = await client.request('agents_list')expect(listed.agents).toHaveLength(3)const worker = listed.agents.find((a: Record<string, any>) => a.id === starts.get('start-claude')!.harnessId)+ await until('host to retain contributed members independently of open panes', () =>+ agents.every(a => retainedHarnesses(d.dataDir).has(a.harnessId)) || null, 10_000, 100)assignments.push({ tabId: TAB, assignmentId: 'worker-attempt', harnessId: worker.id })const closed = await client.request('agent_close', { agentId: worker.id, sessionId: worker.sessionId, createdAt: worker.createdAt, mode: 'now' }, 60_000)expect(closed, JSON.stringify(closed)).toMatchObject({ closed: true })@@ -263,6 +266,22 @@ it('starts either engine once, posts to its captured group and delivers shared iexpect(stopReceipts[0]).toMatchObject({ assignmentId: 'worker-attempt', receipt: expect.stringContaining('native-stopped:') })expect(await client.request('super_tabs', { action: 'observeCapacity', creationId: starts.get('start-claude')!.creationId })).toMatchObject({ ok: true, harnessId: worker.id, released: true })+ // A member may have stopped under an older build. The app resumes the same+ // saved session before preparing a new recording context, never a new worker.+ const reopened = await client.request('agent_resume', { agentId: worker.id, creationId: 'super-tab-resume-worker' }, 90_000)+ expect(reopened.error, JSON.stringify(reopened)).toBeUndefined()+ const resumed = await until('the exact contributed conversation to resume', async () => {+ const rows = (await client.request('agents_list')).agents+ const row = rows.find((a: Record<string, any>) => a.id === worker.id)+ return row?.status === 'active' && row.sessionId === worker.sessionId ? row : null+ }, 60_000, 250)+ expect(resumed.id).toBe(worker.id)+ const reopenContext = 'native-resumed-worker-context'+ expect(await client.request('super_tabs', { action: 'backend', method: 'POST', path: `/api/super-tabs/${TAB}/native`,+ body: { operationId: reopenContext, conversationId: 'feature', agentId: idFor(worker.id) } }))+ .toMatchObject({ ok: true, value: { contextId: reopenContext } })+ expect(await client.request('super_tabs', { action: 'prepareNative', tabId: TAB, contextId: reopenContext }))+ .toMatchObject({ ok: true, inputContext: reopenContext })// Two callers see the same free memory. Only one may reserve most of it,// even though neither has started its native process yet.const capacity = await client.request('super_tabs', { action: 'capacity', cwd })diff --git a/cli/src/services/agentCleanup.spec.ts b/cli/src/services/agentCleanup.spec.tsindex 1b51e3b91..1eb904c30 100644--- a/cli/src/services/agentCleanup.spec.ts+++ b/cli/src/services/agentCleanup.spec.ts@@ -6,6 +6,7 @@ import { emptyPorts } from '../core/api.js'import type { AgentCloseResult } from '../lib/closeAgentService.js'import type { RegisteredSession } from '../lib/registry.js'import { fakeCore } from '../testing/fakeCore.js'+import { retainContributions } from '../superTabs/retention.js'import { ASK_AGAIN_MS, CASCADE_RETRY_MS, CASCADE_TRIES, createAgentCleanup, IDLE_CLOSE_MS, JOINED_MAX, joinedPath, LOOK_EVERY_MS, startAgentCleanup, type AgentCleanupDeps } from './agentCleanup.js'const NOW = Date.parse('2026-10-12T12:00:00Z')@@ -52,6 +53,51 @@ function setup(sessions: RegisteredSession[], quietFor: Record<string, number |/** Lets the closes a notice started finish. */const settle = () => new Promise((done) => setTimeout(done, 0))+it('keeps idle Super Tab members through host restarts and starter closure, until their contribution is removed', async () => {+ const sessions = [kid('member'), kid('ordinary')]+ const t = setup(sessions, { member: 2 * IDLE_CLOSE_MS, ordinary: 2 * IDLE_CLOSE_MS })+ retainContributions(dir, 'machine-1', [{ tabId: 'tab', agent: { harnessId: 'member', machineId: 'machine-1' } }])+ await t.cleanup.look()+ t.advance(IDLE_CLOSE_MS)+ await t.cleanup.look()+ expect(t.closeStarted.mock.calls).toEqual([['ordinary', 'idle']])+ await t.cleanup.closeStartedBy('lead')+ expect(sessions.map(s => s.agentId)).toEqual(['member'])+ t.cleanup.port.stop()+ const restarted = setup(sessions, { member: 2 * IDLE_CLOSE_MS })+ await restarted.cleanup.look()+ restarted.advance(IDLE_CLOSE_MS)+ await restarted.cleanup.look()+ expect(restarted.closeStarted).not.toHaveBeenCalled()+ retainContributions(dir, 'machine-1', [])+ await restarted.cleanup.look()+ expect(restarted.closeStarted.mock.calls).toEqual([['member', 'idle']])+ restarted.cleanup.port.stop()+})++it('rechecks retention after waiting on activity or another orphan close', async () => {+ const t = setup([kid('member')], { member: 2 * IDLE_CLOSE_MS })+ await t.cleanup.look()+ t.advance(IDLE_CLOSE_MS)+ t.lastActivity.mockImplementationOnce(async () => {+ retainContributions(dir, 'machine', [{ tabId: 'tab', agent: { harnessId: 'member', machineId: 'machine' } }])+ return NOW - IDLE_CLOSE_MS+ })+ await t.cleanup.look()+ expect(t.closeStarted).not.toHaveBeenCalled()+ expect(t.log).not.toHaveBeenCalled()+ retainContributions(dir, 'machine', [])+ const cascade = setup([kid('first'), kid('member')])+ cascade.closeStarted.mockImplementationOnce(async () => {+ retainContributions(dir, 'machine', [{ tabId: 'tab', agent: { harnessId: 'member', machineId: 'machine' } }])+ return { closed: true }+ })+ await cascade.cleanup.closeStartedBy('lead')+ expect(cascade.closeStarted.mock.calls).toEqual([['first', 'now']])+ t.cleanup.port.stop()+ cascade.cleanup.port.stop()+})+describe('closing the harnesses a closed harness started', () => {it('closes them now, working or not, with one line each, and only those another agent started there', async () => {// Lead itself is gone: it was closed.diff --git a/cli/src/services/agentCleanup.ts b/cli/src/services/agentCleanup.tsindex 77d021df9..26236bdea 100644--- a/cli/src/services/agentCleanup.ts+++ b/cli/src/services/agentCleanup.ts@@ -16,6 +16,8 @@* - **Never the person's.** Neither touches a harness the person typed or pasted into from a window or the phone: it is* theirs from then on, and kept so in `<data>/agent-cleanup.json` across restarts. A harness the person started is* never one this may close: the core refuses (`CoreApi.agents.closeStarted`).+ * - **Keep shared members.** Super Tab membership also protects a harness from both forms of cleanup, even when its+ * terminal is hidden or its host is offline. Only a confirmed roster removal releases that protection.** A close keeps the conversation, as `harness close` does: the person can resume it, and `harness show` still reads its* answer. One line in the log for each close.@@ -25,6 +27,7 @@ import { dirname, join } from 'node:path'import type { AgentCleanupPort, CoreApi, CorePorts } from '../core/api.js'import type { AgentCloseResult } from '../lib/closeAgentService.js'import type { RegisteredSession } from '../lib/registry.js'+import { retainedHarnesses } from '../superTabs/retention.js'/** How long a harness another agent started may sit idle after its last answer before it is closed. */export const IDLE_CLOSE_MS = 30 * 60_000@@ -103,6 +106,9 @@ export function createAgentCleanup(core: CoreApi, deps: AgentCleanupDeps = {}) {/** Closes [s] as the core lets this; a close done is said. */const close = async (s: RegisteredSession, mode: 'idle' | 'now', why: string): Promise<AgentCloseResult> => {+ // Recheck after an activity read: a shared team may have adopted this agent+ // while cleanup was waiting. This is independent of visible terminal panes.+ if (retainedHarnesses(core.dataDir).has(s.agentId)) return { error: 'SESSION_RETAINED' }const result: AgentCloseResult = await (core.agents.closeStarted?.(s.agentId, mode) ?? Promise.resolve({ error: 'UNSUPPORTED' }))if (result.closed) log(`[agent-cleanup] closed ${label(s)}: ${why}. Its conversation is kept.`)return result@@ -123,12 +129,13 @@ export function createAgentCleanup(core: CoreApi, deps: AgentCleanupDeps = {}) {const live = core.agents.live()// Its starter is back (resumed while this notice was held, or between tries): its harnesses are its again.if (live.some((s) => s.agentId === parentId)) return- const orphans = live.filter((s) => s.parentAgentId === parentId && s.startedBy === 'agent' && !joined.has(s.agentId))+ const retained = retainedHarnesses(core.dataDir)+ const orphans = live.filter((s) => s.parentAgentId === parentId && s.startedBy === 'agent' && !joined.has(s.agentId) && !retained.has(s.agentId))const left: Array<[RegisteredSession, AgentCloseResult]> = []// One at a time: each close saves a screen and stops a process, and a starter may have several.for (const s of orphans) {const result = await close(s, 'now', STARTER_CLOSED)- if (!result.closed) left.push([s, result])+ if (!result.closed && result.error !== 'SESSION_RETAINED') left.push([s, result])}if (!left.length || stopped) returnif (attempt >= CASCADE_TRIES) {@@ -146,6 +153,7 @@ export function createAgentCleanup(core: CoreApi, deps: AgentCleanupDeps = {}) {try {await refresh()const live = core.agents.live()+ const retained = retainedHarnesses(core.dataDir)const gone = (id: string) => !live.some((s) => s.agentId === id)for (const id of askAgainAt.keys()) if (gone(id)) askAgainAt.delete(id)for (const id of said) if (gone(id)) said.delete(id)@@ -154,7 +162,7 @@ export function createAgentCleanup(core: CoreApi, deps: AgentCleanupDeps = {}) {for (const s of live) if (!seen.has(incarnation(s))) seen.set(incarnation(s), now())for (const s of live) {if (stopped) return- if (s.startedBy !== 'agent' || joined.has(s.agentId) || (askAgainAt.get(s.agentId) ?? 0) > now()) continue+ if (s.startedBy !== 'agent' || joined.has(s.agentId) || retained.has(s.agentId) || (askAgainAt.get(s.agentId) ?? 0) > now()) continue// Not before this run of it has been here that long; then by when its conversation last moved, its last answer// or later. Not known (an engine that keeps no dated transcript), it is left alone.const since = seen.get(incarnation(s))!@@ -168,7 +176,7 @@ export function createAgentCleanup(core: CoreApi, deps: AgentCleanupDeps = {}) {if (result.closed) continueaskAgainAt.set(s.agentId, now() + ASK_AGAIN_MS)// Working after all, or waiting for the person: asked again later, nothing to say. Anything else is said once.- if (result.error !== 'SESSION_NOT_IDLE' && !said.has(s.agentId)) {+ if (result.error !== 'SESSION_NOT_IDLE' && result.error !== 'SESSION_RETAINED' && !said.has(s.agentId)) {said.add(s.agentId)failed(s, why, result)}diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex a4ba7311b..0e5069162 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -1,10 +1,11 @@-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import type { CoreApi, TurnDelivery } from '../core/api.js'import { fakeCore } from '../testing/fakeCore.js'import { backend, hostJournalFile, SuperTabHost } from './host.js'+import { retainedHarnesses, retentionFile } from './retention.js'const roots: string[] = []const hosts: SuperTabHost[] = []@@ -43,6 +44,29 @@ function setup(messageFields: Record<string, unknown> = {}) {}describe('Super Tab native delivery handoff', () => {+ it('keeps roster members through host failure and restart, releasing only a confirmed removal', async () => {+ const t = setup(), first = t.open()+ await first.tick()+ expect(retainedHarnesses(t.dir).has('harness')).toBe(true)+ first.stop()+ expect(retainedHarnesses(t.dir).has('harness')).toBe(true)+ const next = t.open()+ vi.mocked(t.call).mockRejectedValueOnce(new Error('Host offline'))+ await next.tick()+ expect(retainedHarnesses(t.dir).has('harness')).toBe(true)+ t.remove()+ await next.tick()+ expect(retainedHarnesses(t.dir).size).toBe(0)+ })+ it('keeps delivering when retention cannot be saved, and says so once', async () => {+ const t = setup(), log = vi.fn()+ mkdirSync(`${retentionFile(t.dir)}.next`, { recursive: true })+ const host = new SuperTabHost(t.core, 'machine-1', { log }); hosts.push(host)+ await host.tick(); await host.tick()+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)+ expect(t.core.turns.leaseDeliveries).toHaveBeenCalled()+ expect(log).toHaveBeenCalledTimes(1)+ })it('preserves the exact reply reference when a short human answer reaches an agent', async () => {const t = setup({ replyTo: 'question-2', text: 'Yes, keep them.' })await t.open().tick()diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 58ec0e358..37df4fc63 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -1,4 +1,5 @@import { publishObservers } from './observers.js'+import { retainContributions } from './retention.js'import { configurationObservation } from './configuration.js'import { NativeRecorder, nativeJournalFile } from './native.js'import { randomUUID } from 'node:crypto'@@ -60,6 +61,7 @@ export class SuperTabHost {private readonly now: () => numberprivate readonly write: (file: string, journal: Journal) => voidprivate readonly log: (message: string) => void+ private retentionError: string | null = nullprivate readonly observers: typeof publishObserversprivate readonly active = new Set<string>()private readonly authorized = new Map<string, number>()@@ -205,6 +207,17 @@ export class SuperTabHost {const data = await backend(this.core, 'GET', `/api/super-tabs/hosts/${this.machineId}`)if (this.stopped) returnif (!Array.isArray(data)) throw new Error('Invalid Super Tab host roster.')+ // Multiply was closed by the ordinary 30-minute idle cleanup while still a+ // shared member. Membership outlives its task, terminal view and host process.+ // Retention only pauses cleanup when it fails; it must never hold up delivery.+ try {+ retainContributions(this.core.dataDir, this.machineId, data)+ this.retentionError = null+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error)+ if (message !== this.retentionError) this.log(message)+ this.retentionError = message+ }this.observers(this.core.dataDir, this.machineId, data, requestedAt + 2500)// Runtime observations cannot delay the live input leases. A stale host// observation is fenced by the backend's per-agent configuration version.diff --git a/cli/src/superTabs/retention.spec.ts b/cli/src/superTabs/retention.spec.tsnew file mode 100644index 000000000..2571ed06d--- /dev/null+++ b/cli/src/superTabs/retention.spec.ts@@ -0,0 +1,60 @@+import { mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, expect, it } from 'vitest'+import { RETENTION_LAPSE_MS, retainContributions, retainedHarnesses, retentionFile } from './retention.js'++const roots: string[] = []+const root = () => { const dir = mkdtempSync(join(tmpdir(), 'super-retention-')); roots.push(dir); return dir }+const row = (harnessId: string, extra: Record<string, unknown> = {}, machineId = 'machine') => ({ tabId: 'tab', agent: { harnessId, machineId }, ...extra })+afterEach(() => { for (const dir of roots.splice(0)) rmSync(dir, { recursive: true, force: true }) })++it('retains exact members durably, avoids unchanged writes and releases only the confirmed host roster', () => {+ const dir = root(), now = Date.now()+ expect([...retainedHarnesses(dir)]).toEqual([])+ retainContributions(dir, 'machine', [row('multiply'), row('divide'), row('multiply')], now)+ expect([...retainedHarnesses(dir, now)]).toEqual(['divide', 'multiply'])+ const file = retentionFile(dir), before = statSync(file, { bigint: true }).mtimeNs+ retainContributions(dir, 'machine', [row('divide'), row('multiply')], now + 1000)+ expect(statSync(file, { bigint: true }).mtimeNs).toBe(before)+ expect(statSync(file).mode & 0o777).toBe(0o600)+ retainContributions(dir, 'machine', [], now)+ expect([...retainedHarnesses(dir, now)]).toEqual([])+})++it('retains paused-tab members but not members of only archived groups or rows for another machine', () => {+ const dir = root(), now = Date.now()+ retainContributions(dir, 'machine', [row('kept'), row('legacy', { active: undefined }), row('paused', { paused: true }),+ row('archived', { active: false }), row('foreign', {}, 'other'), {}, row('../bad')], now)+ expect([...retainedHarnesses(dir, now)]).toEqual(['kept', 'legacy', 'paused'])+ expect(() => retainContributions(dir, '../bad', [])).toThrow()+})++it('lets a new machine identity replace the old entry, and lapses a roster nobody confirms', () => {+ const dir = root(), now = Date.now(), file = retentionFile(dir)+ retainContributions(dir, 'old-machine', [row('combine', {}, 'old-machine')], now)+ retainContributions(dir, 'machine', [row('multiply')], now)+ expect([...retainedHarnesses(dir, now)]).toEqual(['multiply'])+ // An unchanged roster refreshes the lapse clock at most hourly, without rewriting.+ const content = readFileSync(file, 'utf8')+ retainContributions(dir, 'machine', [row('multiply')], now + 2 * 60 * 60_000)+ expect(readFileSync(file, 'utf8')).toBe(content)+ expect(Math.abs(statSync(file).mtimeMs - (now + 2 * 60 * 60_000))).toBeLessThan(1000)+ expect([...retainedHarnesses(dir, now + 2 * 60 * 60_000 + RETENTION_LAPSE_MS - 1000)]).toEqual(['multiply'])+ expect([...retainedHarnesses(dir, now + 2 * 60 * 60_000 + RETENTION_LAPSE_MS + 1000)]).toEqual([])+})++it('pauses cleanup on corrupt or oversized retention until the host rewrites it or it lapses', () => {+ const dir = root(), file = retentionFile(dir), now = Date.now()+ retainContributions(dir, 'machine', [row('multiply')], now)+ for (const value of ['{', '{}', '{"version":1,"machines":{}}', '{"version":2,"machineId":"machine","harnesses":[null]}', ' '.repeat(4 * 1024 * 1024 + 1)]) {+ writeFileSync(file, value)+ utimesSync(file, new Date(now), new Date(now))+ expect(() => retainedHarnesses(dir, now)).toThrow('Automatic cleanup is paused')+ expect([...retainedHarnesses(dir, now + RETENTION_LAPSE_MS + 1)]).toEqual([])+ }+ retainContributions(dir, 'machine', [row('multiply')], now)+ expect([...retainedHarnesses(dir, now)]).toEqual(['multiply'])+ unlinkSync(file)+ expect([...retainedHarnesses(dir, now)]).toEqual([])+})diff --git a/cli/src/superTabs/retention.ts b/cli/src/superTabs/retention.tsnew file mode 100644index 000000000..bf15031e1--- /dev/null+++ b/cli/src/superTabs/retention.ts@@ -0,0 +1,57 @@+/** A shared contribution belongs to its Super Tab even while no terminal is shown.+ * Keep the last confirmed roster across host/network restarts; only a successful+ * roster read may release it to automatic cleanup. This grants no input access.+ *+ * Membership only in archived groups is not in use, and a roster nobody confirms+ * for a week (signed out, unlinked machine) lapses. A paused tab still counts:+ * pause blocks new work, while discussion and running assignments continue. */+import { existsSync, mkdirSync, readFileSync, renameSync, statSync, utimesSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { identifier, object } from './wire.js'++interface Retention { version: 2; machineId: string; harnesses: string[] }+export const retentionFile = (dataDir: string) => join(dataDir, 'super-tabs', 'retained.json')+export const RETENTION_LAPSE_MS = 7 * 24 * 60 * 60_000+const REFRESH_MS = 60 * 60_000++function read(file: string): Retention {+ if (statSync(file).size > 4 * 1024 * 1024) throw new Error('Super Tab retention is too large. Automatic cleanup is paused.')+ let value: Record<string, unknown> = {}+ try { value = object(JSON.parse(readFileSync(file, 'utf8'))) } catch { /* reported below */ }+ if (value.version !== 2 || !identifier(value.machineId) || !Array.isArray(value.harnesses) || !value.harnesses.every(identifier)) {+ throw new Error('Super Tab retention is unreadable. Automatic cleanup is paused.')+ }+ return value as unknown as Retention+}++export function retainedHarnesses(dataDir: string, now = Date.now()): Set<string> {+ const file = retentionFile(dataDir)+ // An unreadable file fails closed only until it lapses; the host rewrites it on its next roster.+ if (!existsSync(file) || now - statSync(file).mtimeMs > RETENTION_LAPSE_MS) return new Set()+ return new Set(read(file).harnesses)+}++export function retainContributions(dataDir: string, machineId: string, rows: unknown[], now = Date.now()): void {+ if (!identifier(machineId)) throw new Error('Invalid Super Tab retention machine.')+ const ids = new Set<string>()+ for (const item of rows) {+ const row = object(item), agent = object(row.agent)+ if (!identifier(row.tabId) || !identifier(agent.harnessId) || agent.machineId !== machineId) continue+ if (row.active === false) continue+ ids.add(agent.harnessId)+ }+ const file = retentionFile(dataDir)+ const next: Retention = { version: 2, machineId, harnesses: [...ids].sort() }+ // This machine's confirmed roster is authoritative: it replaces an unreadable+ // file and another identity's entry. Unchanged rosters only refresh the lapse clock.+ let previous: Retention | null = null+ try { if (existsSync(file)) previous = read(file) } catch { /* rebuilt below */ }+ if (previous && JSON.stringify(previous) === JSON.stringify(next)) {+ if (now - statSync(file).mtimeMs > REFRESH_MS) utimesSync(file, new Date(now), new Date(now))+ return+ }+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })+ writeFileSync(`${file}.next`, JSON.stringify(next), { mode: 0o600, flush: true })+ renameSync(`${file}.next`, file)+ utimesSync(file, new Date(now), new Date(now))+}diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.mdindex 76be7cbb9..2d36aeeb6 100644--- a/desktop/design/terminal-workspace.md+++ b/desktop/design/terminal-workspace.md@@ -24,6 +24,19 @@ the session, using the existing confirmation when it is working. A tab closeapplies this rule separately to each session. Recheck remaining views afterany wait for inspection or confirmation, before requesting a stop.+Super Tab terminals are views of shared work. Their close control says **Hide+terminal**; it dismisses the local view without inspecting, prompting to stop,+or stopping the agent. The close shortcut and closing the Super Tab follow the+same rule. The agent remains in its conversation and its terminal can be reopened.+The coordinating agent is labeled **Lead** throughout the Super Tab, including+its terminal header; its first message is not its name.+Super Tab membership protects an agent from automatic idle and parent cleanup,+including while the host is offline and while the Super Tab is paused. Membership+only in archived conversations does not, and protection lapses after a week without a+confirmed roster (for example after sign-out). If the agent is already stopped,+only **Open terminal** (in Participants or on a message) resumes its saved conversation; a restored+or revisited terminal selection closes instead, so an explicit stop stays stopped.+## Keep the workspace structureTabs remain compact and content-sized, adding one at a time until the row fills.diff --git a/desktop/integration_test/super_tab_native_test.dart b/desktop/integration_test/super_tab_native_test.dartindex 2a12f3245..4551eb154 100644--- a/desktop/integration_test/super_tab_native_test.dart+++ b/desktop/integration_test/super_tab_native_test.dart@@ -12,6 +12,8 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/new_harness.dart';import 'package:harness/super_tabs/workspace.dart';import 'package:harness/widgets/pane_grid.dart';+import 'package:harness/widgets/agent_drag.dart';+import 'package:harness/widgets/terminal_panel.dart';import '../test/super_tab_launch_test.dart'show SuperTabFixtureConnection, SuperTabLaunchFixture, tabId;@@ -36,6 +38,7 @@ void main() {await windowManager.focus().timeout(const Duration(seconds: 10));debugPrint('Super Tab fixture: create lead');final f = SuperTabLaunchFixture();+ f.connection.nativeName = 'hi';f.connection.nativeSurface = true;f.app.machineStates['m']!.terminalCapabilityAvailable = true;await tester.runAsync(() async {@@ -176,8 +179,79 @@ void main() {debugPrint('Super Tab fixture: terminal ready');await shot('terminal');expect(find.byType(PaneGrid), findsOneWidget);+ expect(+ tester+ .widget<Text>(find.byKey(const ValueKey('terminal-pane-title')))+ .data,+ 'Lead',+ );+ var reviews = 0;+ f.app.reviewSessionClose = (_, {tabName, canStop}) async {+ reviews++;+ return false;+ };+ await tester.tap(find.byType(PaneCloseButton));+ await tester.pumpAndSettle();+ expect(f.app.activeSwarm.panes, isEmpty);+ expect(c!.terminalAgent('lead'), isNull);+ expect(find.byType(TerminalPanel), findsNothing);+ expect(reviews, 0);+ expect(+ f.connection.calls.where((call) => call.$1 == 'agent_close'),+ isEmpty,+ );+ expect(c.snapshot!.agents, hasLength(1));+ await shot('hidden-terminal');+ // An earlier app/daemon may already have cleaned up this member. Reopening+ // must resume its exact saved conversation before preparing recording.+ f.connection.native = {+ ...f.connection.native!,+ 'status': 'stopped',+ 'sessionId': 'saved-native-conversation',+ 'terminal': {'available': false},+ };+ f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];+ await tester.tap(find.text('1 agent · 20 people'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Open terminal'));+ for (+ var i = 0;+ i < 120 &&+ (f.app.activeSwarm.panes.isEmpty ||+ f.app.activeSwarm.panes.single.session?.streamId == null);+ i+++ ) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ expect(+ f.app.activeSwarm.panes,+ hasLength(1),+ reason:+ 'Reopen failed: ${f.connection.calls}\n'+ '${tester.widgetList<Text>(find.byType(Text)).map((text) => text.data).whereType<String>().join("\n")}',+ );+ expect(f.app.activeSwarm.panes.single.agentId, 'native-lead');+ expect(+ f.app.activeSwarm.panes.single.session?.streamId,+ SuperTabFixtureConnection.streamId,+ );+ expect(+ f.connection.calls.where((call) => call.$1 == 'agent_create'),+ hasLength(1),+ );+ expect(+ f.connection.calls.where((call) => call.$1 == 'agent_resume'),+ hasLength(1),+ );+ expect(+ f.app.stateOf('m')!.agents.single.sessionId,+ 'saved-native-conversation',+ );+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.byType(TerminalPanel), findsOneWidget);+ await shot('resumed-terminal');await tester.pumpWidget(const SizedBox());- await c!.flush();+ await c.flush();f.app.superTabs.dispose();await tester.pump();},diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 55c7e9f5c..8a8af57e7 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -3055,8 +3055,8 @@ class AppNotifier extends ChangeNotifier {}}- /// Close removes these views. A session stops only when this removes its- /// last view across all tabs; shared views keep their live terminal.+ /// Close removes these views. Super Tabs own work independently of their+ /// views; ordinary tabs stop a session only when its last view closes.Future<void> requestCloseSwarm(String id) {final tab = swarms.where((s) => s.id == id).firstOrNull;if (tab == null) return Future.value();@@ -3108,6 +3108,10 @@ class AppNotifier extends ChangeNotifier {if (_disposed) return Future.value();if (_viewCloseRequests[key] case final pending?) return pending;bool canStop(String machineId, String agentId) {+ // A Super Tab pane is only a view into shared work. This guard also covers+ // the close shortcut, native menu and whole-tab dismissal, including a+ // regular tab becoming a Super Tab while a close review is pending.+ if (tab.isSuperTab) return false;if (!swarms.contains(tab) ||(wholeTab &&(tab.panes.length != closing.length ||diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex e7e595475..309e25464 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -178,7 +178,7 @@ class SuperTabLaunch {'conversationId': saved['conversationId'],'machineId': machine,'harnessId': harnessId,- 'name': native.displayName,+ 'name': saved['lead'] == true ? 'Lead' : native.displayName,'lead': saved['lead'],'configuration': {'engine': native.engine ?? '',diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 5f70260ef..0d37d2add 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -21,6 +21,7 @@ class SuperTabMessageRow extends StatefulWidget {this.agent,this.machineName,this.reply,+ this.replyAuthor,this.grouped = false,this.onReply,});@@ -30,6 +31,7 @@ class SuperTabMessageRow extends StatefulWidget {final SuperTabAgent? agent;final String? machineName;final SuperTabMessage? reply;+ final String? replyAuthor;final bool grouped;final VoidCallback? onReply;final VoidCallback onReturnToComposer;@@ -188,7 +190,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {child: message.fromAgent? EngineMark(engine: widget.agent?.engine,- displayName: message.authorName,+ displayName: widget.author,size: 28,): AccountAvatar(@@ -251,6 +253,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {padding: const EdgeInsets.only(bottom: 8),child: SuperTabReplyPreview(author:+ widget.replyAuthor ??widget.reply?.authorName ??'Earlier message',text:diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex d9da4e3b1..00c18486a 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -89,6 +89,16 @@ class SuperTabSnapshot {conversations.where((c) => c.id == id).firstOrNull;SuperTabAgent? agent(String id) =>agents.where((a) => a.id == id).firstOrNull;++ bool isLead(String agentId) => conversation('lead')?.leadId == agentId;++ String agentName(String id, {String fallback = 'Agent'}) =>+ isLead(id) ? 'Lead' : agent(id)?.name ?? fallback;++ String authorName(SuperTabMessage message) =>+ message.fromAgent && isLead(message.authorId)+ ? 'Lead'+ : message.authorName;}class SuperTabMessage {diff --git a/desktop/lib/super_tabs/pane.dart b/desktop/lib/super_tabs/pane.dartnew file mode 100644index 000000000..169813280--- /dev/null+++ b/desktop/lib/super_tabs/pane.dart@@ -0,0 +1,29 @@+import 'package:flutter/widgets.dart';++/// A Super Tab's view of an existing terminal. The renderer and session stay+/// shared with ordinary panes; presentation belongs to this placement only.+/// AppNotifier's close policy keeps pane, keyboard and tab dismissal hide-only.+class SuperPane extends InheritedWidget {+ const SuperPane({+ super.key,+ required this.machineId,+ required this.harnessId,+ this.title,+ required super.child,+ });++ final String machineId, harnessId;+ final String? title;++ static SuperPane? maybeOf(BuildContext context) =>+ context.dependOnInheritedWidgetOfExactType<SuperPane>();++ String? titleFor(String machine, String harness) =>+ machine == machineId && harness == harnessId ? title : null;++ @override+ bool updateShouldNotify(SuperPane oldWidget) =>+ machineId != oldWidget.machineId ||+ harnessId != oldWidget.harnessId ||+ title != oldWidget.title;+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex d3b5f4f3f..6b16b8104 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -57,6 +57,12 @@ class _SuperTabViewState extends State<SuperTabView> {String? _dismissedMention;SuperTabController get c => widget.controller;+ String _agentName(SuperTabAgent agent) =>+ c.snapshot?.agentName(agent.id, fallback: agent.name) ?? agent.name;++ String _authorName(SuperTabMessage message) =>+ c.snapshot?.authorName(message) ?? message.authorName;+@overridevoid initState() {super.initState();@@ -232,7 +238,7 @@ class _SuperTabViewState extends State<SuperTabView> {.where((agent) =>c.selected?.agentIds.contains(agent.id) == true &&- '${agent.name} ${agent.engine}'.toLowerCase().contains(+ '${_agentName(agent)} ${agent.engine}'.toLowerCase().contains(mention.query,),)@@ -244,7 +250,7 @@ class _SuperTabViewState extends State<SuperTabView> {void _chooseMention(SuperTabAgent agent) {final at = _mentionAtCursor;if (at == null) return;- final token = '@${agent.name}';+ final token = '@${_agentName(agent)}';final text = _composer.text.replaceRange(at.start, at.end, '$token ');c.setDraft(c.selectedId, text);c.mention(c.selectedId, agent.id, token);@@ -469,7 +475,7 @@ class _SuperTabViewState extends State<SuperTabView> {.where((a) =>currentGroup.agentIds.contains(a.id) &&- '${a.name} ${a.engine} ${widget.machineName(a.machineId)}'+ '${_agentName(a)} ${a.engine} ${widget.machineName(a.machineId)}'.toLowerCase().contains(query),)@@ -593,7 +599,7 @@ class _SuperTabViewState extends State<SuperTabView> {crossAxisAlignment: CrossAxisAlignment.start,mainAxisSize: MainAxisSize.min,children: [- Text(agent.name, style: DesktopChrome.control(medium: true)),+ Text(_agentName(agent), style: DesktopChrome.control(medium: true)),const SizedBox(height: 4),Text('${engineIdentity(agent.engine).label} · ${widget.machineName(agent.machineId)}',@@ -935,7 +941,8 @@ class _SuperTabViewState extends State<SuperTabView> {): AlertDialog(title: DesktopDialogHeader(- title: 'Check delivery to ${agent?.name ?? 'agent'}',+ title:+ 'Check delivery to ${agent == null ? 'agent' : _agentName(agent)}',padding: EdgeInsets.zero,onClose: () => Navigator.pop(context),),@@ -1014,16 +1021,18 @@ class _SuperTabViewState extends State<SuperTabView> {final agent = message.fromAgent? c.snapshot?.agent(message.authorId): null;+ final reply = byId[message.replyTo];return SuperTabMessageRow(key: ValueKey('super-message-${message.id}'),message: message,author: message.authorId == c.accountId && !message.fromAgent? 'You'- : message.authorName,+ : _authorName(message),agent: agent,machineName: agent == null ? null : widget.machineName(agent.machineId),grouped: grouped,- reply: byId[message.replyTo],+ reply: reply,+ replyAuthor: reply == null ? null : _authorName(reply),onReply: c.canWrite && c.selected?.archived == false? () {setState(() => _replies[c.selectedId] = message);@@ -1056,7 +1065,7 @@ class _SuperTabViewState extends State<SuperTabView> {? () => _reviewDelivery(message, delivery): null,child: Text(- 'Check delivery to ${c.snapshot?.agent(delivery['agentId'] as String)?.name ?? 'agent'}',+ 'Check delivery to ${c.snapshot?.agentName(delivery['agentId'] as String, fallback: 'agent') ?? 'agent'}',),),],@@ -1235,7 +1244,7 @@ class _SuperTabViewState extends State<SuperTabView> {children: [Expanded(child: SuperTabReplyPreview(- author: 'Replying to ${reply.authorName}',+ author: 'Replying to ${_authorName(reply)}',text: reply.text,),),@@ -1261,7 +1270,7 @@ class _SuperTabViewState extends State<SuperTabView> {dense: true,selected:i == _mentionIndex.clamp(0, mentions.length - 1),- title: Text(mentions[i].name),+ title: Text(_agentName(mentions[i])),subtitle: Text('${mentions[i].engine} · ${widget.machineName(mentions[i].machineId)}',),diff --git a/desktop/lib/super_tabs/work_details.dart b/desktop/lib/super_tabs/work_details.dartindex 3e883295c..6e2088dc0 100644--- a/desktop/lib/super_tabs/work_details.dart+++ b/desktop/lib/super_tabs/work_details.dart@@ -35,7 +35,7 @@ Future<void> showSuperTabWork(if (assignment != null) ...[const SizedBox(height: 16),Text(- '${c.snapshot?.agent(assignment['agentId'] as String)?.name ?? 'Agent unavailable'} · ${(assignment['status'] as String).replaceAll('_', ' ')}',+ '${c.snapshot?.agentName(assignment['agentId'] as String, fallback: 'Agent unavailable') ?? 'Agent unavailable'} · ${(assignment['status'] as String).replaceAll('_', ' ')}',),],for (final checkdiff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dartindex db2bf4317..4cbf586ee 100644--- a/desktop/lib/super_tabs/workspace.dart+++ b/desktop/lib/super_tabs/workspace.dart@@ -10,6 +10,7 @@ import '../widgets/desktop_chrome.dart';import 'controller.dart';import 'dialog_scope.dart';import 'model.dart';+import 'pane.dart';import 'view.dart';/// Keeps the app's one native canvas alive while placing it beside a shared@@ -34,6 +35,10 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {AppNotifier get app => widget.app;(String, String, String?, String, bool)? _terminalRequest;(String, String, String?, String, bool)? _readyRequest;+ // Only Open terminal (Participants or a message) may relaunch a stopped+ // member. A restored or revisited selection must not undo `harness close`+ // or a person's stop.+ (String, String)? _resumeRequest;Future<void> _terminalChange = Future.value();TerminalPane? _nativePane;Timer? _nativeHeartbeat;@@ -74,6 +79,9 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {if (_terminalRequest == request) return;_clearNativeContext();_terminalRequest = request;+ final resume =+ agent != null && _resumeRequest == (controller.selectedId, agent.id);+ _resumeRequest = null;bool current() =>mounted &&_terminalRequest == request &&@@ -88,7 +96,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {) async {if (!current()) return;if (agent != null) {- await _open(agent, controller, swarmId, request.$2, current);+ await _open(agent, controller, swarmId, request.$2, current, resume);if (current()) setState(() => _readyRequest = request);} else {final tab = app.swarms.where((s) => s.id == swarmId).firstOrNull;@@ -107,6 +115,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {String swarmId,String conversationId,bool Function() current,+ bool resume,) async {try {final tab = app.swarms.where((s) => s.id == swarmId).firstOrNull;@@ -128,6 +137,27 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {// A narrowly shared harness remains its existing read-only observer.// Controlling a machine and joining a Super Tab are separate grants.if (controller.canWrite && machine?.machine.isShared != true) {+ final stopped = machine?.agents+ .where((a) => a.id == agent.harnessId)+ .firstOrNull+ ?.isStopped;+ if (stopped == true) {+ if (!resume) {+ controller.selectTerminal(conversationId, null);+ return;+ }+ // Older idle cleanup may already have stopped a contributed harness.+ // Open its saved conversation through the existing resume receipt+ // before issuing a native context, so a failed resume leaves none.+ final resumeError = await app.resumeStoppedSession(+ agent.machineId,+ agent.harnessId,+ );+ if (!current()) return;+ if (resumeError != null) {+ throw SuperTabFailure('TERMINAL_UNAVAILABLE', resumeError);+ }+ }final issued = await controller.request('POST','/api/super-tabs/${controller.tabId}/native',@@ -254,10 +284,21 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {pane.machineId == selectedTerminal.machineId &&pane.agentId == selectedTerminal.harnessId,);+ final terminal = selectedTerminal == null+ ? canvas+ : SuperPane(+ machineId: selectedTerminal.machineId,+ harnessId: selectedTerminal.harnessId,+ title:+ controller.snapshot?.isLead(selectedTerminal.id) == true+ ? 'Lead'+ : null,+ child: canvas,+ );return Stack(fit: StackFit.expand,children: [- if (!showTerminal) Offstage(child: canvas),+ if (!showTerminal) Offstage(child: terminal),SuperTabView(key: ValueKey('${controller.accountId}:$id'),controller: controller,@@ -266,13 +307,14 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {onAddAgent: widget.onAddAgent,onOpenTerminal: (agent) {_terminalRequest = null;+ _resumeRequest = (controller.selectedId, agent.id);controller.selectTerminal(controller.selectedId, agent.id);setState(() {});},machineName: (machine) =>app.stateOf(machine)?.machine.displayName ??'Offline machine',- terminal: showTerminal ? canvas : null,+ terminal: showTerminal ? terminal : null,onCloseTerminal: () {controller.selectTerminal(controller.selectedId, null);},diff --git a/desktop/lib/widgets/agent_drag.dart b/desktop/lib/widgets/agent_drag.dartindex f6aace916..6d1d6b4e1 100644--- a/desktop/lib/widgets/agent_drag.dart+++ b/desktop/lib/widgets/agent_drag.dart@@ -5,6 +5,7 @@ import '../shared/theme/app_pane_icon.dart';import '../shared/theme/app_theme.dart' as grid;import '../shortcuts/app_keymap.dart';+import '../super_tabs/pane.dart';import '../shared/theme/workspace_bar_style.dart';import '../terminal/terminal_theme.dart';import '../terminal/terminal_theme_store.dart';@@ -145,7 +146,7 @@ class PaneCloseButton extends StatelessWidget {@overrideWidget build(BuildContext context) => PaneHeaderButton(- label: 'Close Pane',+ label: SuperPane.maybeOf(context) == null ? 'Close Pane' : 'Hide terminal',command: 'pane.close',icon: AppPaneSymbol.close,iconSize: AppIcons.closeSize,diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 823b2aeac..d3aecf728 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -19,6 +19,7 @@ import '../core/runtime_platform.dart';import '../state/app_state.dart';import '../state/harness_activity.dart';import '../state/model_start_watch.dart';+import '../super_tabs/pane.dart';import 'agent_drag.dart';import 'box_chrome.dart';@@ -2470,7 +2471,10 @@ class _TerminalPanelState extends State<TerminalPanel>terminalFont: terminalFontStore.value,notifier: widget.notifier,session: session,- name: session.agentName,+ name:+ SuperPane.maybeOf(context)+ ?.titleFor(session.machineId, session.agentId) ??+ session.agentName,status: session.status,notice: widget.notice,readOnly: widget.readOnly || session.readOnly,@@ -2734,6 +2738,9 @@ class _TerminalHeader extends StatelessWidget {.firstOrNull;final project = agent == null ? null : machine?.projectOf(agent);final machineName = machine?.machine.displayName ?? session.machineId;+ final roleTitle = SuperPane.maybeOf(context)+ ?.titleFor(session.machineId, session.agentId);+ final title = roleTitle ?? session.agentName;// Started by another harness's agent: that harness by the name it shows// now, which the person may have changed since. Nothing when it is not// listed here any more: an id would mean nothing to them.@@ -2744,13 +2751,13 @@ class _TerminalHeader extends StatelessWidget {.firstOrNull?.displayName;final identityDetail = [- session.agentName,+ title,if (startedBy != null) 'Started by $startedBy',machineName,if (project != null) project.cwd,?project?.branchDetail,if (profile != null) 'Codex profile: $profile',- 'Double-click to rename',+ if (roleTitle == null) 'Double-click to rename',].join('\n');// Reserve space for the pane-local model selector.// Engines without a picker keep their existing header width.@@ -2812,7 +2819,7 @@ class _TerminalHeader extends StatelessWidget {// side most of the header.double titleRoom() {final name = TextPainter(- text: TextSpan(text: session.agentName, style: titleStyle),+ text: TextSpan(text: title, style: titleStyle),textDirection: TextDirection.ltr,textScaler: MediaQuery.textScalerOf(context),maxLines: 1,@@ -2928,17 +2935,19 @@ class _TerminalHeader extends StatelessWidget {waitDuration: const Duration(milliseconds: 500),child: GestureDetector(behavior: HitTestBehavior.opaque,- onDoubleTap: () => unawaited(- showAgentRenameDialog(- context,- notifier,- session.machineId,- session.agentId,- session.agentName,- ),- ),+ onDoubleTap: roleTitle != null+ ? null+ : () => unawaited(+ showAgentRenameDialog(+ context,+ notifier,+ session.machineId,+ session.agentId,+ session.agentName,+ ),+ ),child: Text(- session.agentName,+ title,key: const ValueKey('terminal-pane-title'),maxLines: 1,overflow: TextOverflow.ellipsis,diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dartindex 6551ad98b..a8ae48a1b 100644--- a/desktop/test/session_close_test.dart+++ b/desktop/test/session_close_test.dart@@ -99,6 +99,37 @@ void main() {tearDown(() => app.dispose());List<Object?> modes() => connection.closes.map((r) => r['mode']).toList();+ for (final wholeTab in [false, true]) {+ test(+ 'closing a Super Tab ${wholeTab ? 'tab' : 'pane'} hides working agents without a stop review',+ () async {+ final tab = app.activeSwarm;+ app.bindSuperTab(tab.id, 'shared-tab', 'Pilot');+ final pane = app.adoptSessionForTest(terminal('a0', []));+ connection.activities['a0'] = 'working';+ var reviews = 0;+ app.reviewSessionClose = (_, {tabName, canStop}) async {+ reviews++;+ return false;+ };+ if (wholeTab) {+ await app.requestCloseSwarm(tab.id);+ expect(app.swarms, isNot(contains(tab)));+ } else {+ await app.requestClosePane(pane.id);+ expect(app.swarms, contains(tab));+ expect(tab.panes, isEmpty);+ }+ expect(reviews, 0);+ expect(connection.closes, isEmpty);+ expect(+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,+ isFalse,+ );+ },+ );+ }+test('without a close presenter an unsupported decision keeps its pane intact',() async {diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dartindex 549d8d29d..eb11760eb 100644--- a/desktop/test/super_tab_chat_test.dart+++ b/desktop/test/super_tab_chat_test.dart@@ -37,6 +37,63 @@ void main() {return c;}+ testWidgets(+ 'an existing lead named after a greeting is Lead in messages, replies and participants',+ (tester) async {+ final server = ConversationServer();+ (server.state['agents'] as List).add({+ 'id': 'lead-agent',+ 'name': 'hi',+ 'machineId': 'm',+ 'harnessId': 'native-lead',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ });+ (server.state['conversations'] as List)[0]+ ..['leadId'] = 'lead-agent'+ ..['agentIds'] = ['lead-agent'];+ server.append('What should we build?');+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'hi',+ };+ final c = await show(tester, server);+ final row = find.byKey(const ValueKey('super-message-message-1'));+ expect(+ find.descendant(of: row, matching: find.text('Lead')),+ findsOneWidget,+ );+ expect(find.text('hi'), findsNothing);+ tester+ .widget<Focus>(+ find.descendant(of: row, matching: find.byType(Focus)).first,+ )+ .focusNode!+ .requestFocus();+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.keyR);+ await tester.pump();+ expect(find.text('Replying to Lead'), findsOneWidget);+ final composer = find.byKey(const ValueKey('super-message-composer'));+ await tester.enterText(composer, 'Let’s discuss the plan.');+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ await c.refresh();+ await tester.pumpAndSettle();+ final reply = find.byKey(const ValueKey('super-message-message-2'));+ expect(+ find.descendant(of: reply, matching: find.text('Lead')),+ findsOneWidget,+ );+ await tester.tap(find.text('1 agent · 1 person'));+ await tester.pumpAndSettle();+ expect(find.text('hi'), findsNothing);+ expect(find.text('Lead'), findsWidgets);+ expect(find.text('Open terminal'), findsOneWidget);+ },+ );+testWidgets('a keyboard reply keeps its quoted context after sending and refreshing',(tester) async {diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dartindex 6f23cd9b9..dc3ee93a4 100644--- a/desktop/test/super_tab_launch_test.dart+++ b/desktop/test/super_tab_launch_test.dart@@ -36,6 +36,7 @@ class SuperTabFixtureConnection extends WsConn {final joins = <Map<String, dynamic>>[];bool loseCreate = false, loseJoin = false;bool failNative = false;+ bool failResume = false;bool nativeSurface = false;bool failFiles = false, failCreation = false, changeAccountOnUpload = false;late AppNotifier app;@@ -43,6 +44,7 @@ class SuperTabFixtureConnection extends WsConn {final terminalCalls = <(String, Map<String, dynamic>)>[];static const streamId = '00112233-4455-6677-8899-aabbccddeeff';Map<String, dynamic>? native;+ String nativeName = 'Lead';Future<void> event(String type, Map<String, dynamic> payload) =>app.handleMachineEventForTest('m', {'type': type, 'payload': payload});@@ -123,6 +125,12 @@ class SuperTabFixtureConnection extends WsConn {if (payload['action'] == 'wake') return {'ok': true};if (payload['action'] == 'prepareNative' ||payload['action'] == 'renewNative') {+ if (native?['status'] == 'stopped') {+ return {+ 'error': 'SUPER_TAB_UNAVAILABLE',+ 'detail': 'The exact contributed terminal is unavailable on this machine.',+ };+ }return failNative? {'error': 'NATIVE_UNAVAILABLE',@@ -152,10 +160,15 @@ class SuperTabFixtureConnection extends WsConn {'id': 'lead-agent','machineId': 'm','harnessId': command['harnessId'],- 'name': 'Lead',+ 'name': command['name'],'contributorId': 'owner','configuration': command['configuration'],});+ final group = (server.state['conversations'] as List)+ .cast<Map>()+ .firstWhere((g) => g['id'] == command['conversationId']);+ (group['agentIds'] as List).add('lead-agent');+ if (command['lead'] == true) group['leadId'] = 'lead-agent';if (command['initialMessage'] is String) {server.append(command['initialMessage'] as String);}@@ -174,6 +187,22 @@ class SuperTabFixtureConnection extends WsConn {}return {'ok': true, 'value': value};}+ if (type == 'agent_resume') {+ // The real native test completes this request during a frame pump.+ expectSync(payload['agentId'], native!['id']);+ if (failResume) return {'error': 'RESUME_FAILED'};+ native = {+ ...native!,+ 'status': 'active',+ 'terminal': {'available': true},+ };+ return {+ 'creationId': payload['creationId'],+ 'state': 'created',+ 'resumed': true,+ 'agent': native,+ };+ }if (type == 'agent_create') {final records = store.values.entries.where((e) => e.key.startsWith('super_tab.launch.'),@@ -184,8 +213,9 @@ class SuperTabFixtureConnection extends WsConn {expect(saved['creationId'], payload['creationId']);native = {'id': 'native-lead',- 'name': 'Lead',+ 'name': nativeName,'engine': payload['engine'],+ 'closeSupported': true,'terminal': {'available': true},'project': {'cwd': '/work/project', 'label': 'Project'},};@@ -429,7 +459,8 @@ void main() {test('$engine lead uses the native form and joins without opening a terminal or another tab',() async {- final f = SuperTabLaunchFixture(), initialTab = f.app.activeSwarmId;+ final f = SuperTabLaunchFixture()..connection.nativeName = 'hi';+ final initialTab = f.app.activeSwarmId;final box = await f.box(engine: engine);expect(box.actionLabel, 'New Super Tab');expect(@@ -440,6 +471,7 @@ void main() {final creates = f.connection.calls.where((c) => c.$1 == 'agent_create');expect(creates, hasLength(1));expect(creates.single.$2['engine'], engine);+ expect(f.connection.joins.single['command']['name'], 'Lead');expect(creates.single.$2['prompt'],contains('Discuss the architecture.'),diff --git a/desktop/test/super_tab_workspace_test.dart b/desktop/test/super_tab_workspace_test.dartindex 980346b9f..68824ddc9 100644--- a/desktop/test/super_tab_workspace_test.dart+++ b/desktop/test/super_tab_workspace_test.dart@@ -1,11 +1,130 @@import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';+import 'package:harness/super_tabs/view.dart';import 'package:harness/super_tabs/workspace.dart';import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;void main() {+ for (final scenario in [+ (engine: 'codex', viewer: false, fail: false),+ (engine: 'claude', viewer: false, fail: false),+ (engine: 'codex', viewer: true, fail: false),+ (engine: 'codex', viewer: false, fail: true),+ ]) {+ testWidgets('opens a stopped member: $scenario', (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ final state = f.connection.server.state;+ state['agents'] = [+ {+ 'id': 'worker',+ 'name': 'Multiply',+ 'machineId': 'm',+ 'harnessId': 'native-worker',+ 'contributorId': 'owner',+ 'configuration': {'engine': scenario.engine},+ },+ ];+ (state['conversations'] as List)[1]['agentIds'] = ['worker'];+ if (scenario.viewer) (state['people'] as List)[0]['role'] = 'viewer';+ f.connection.native = {+ 'id': 'native-worker',+ 'name': 'Multiply',+ 'engine': scenario.engine,+ 'sessionId': 'saved-multiply-conversation',+ 'status': 'stopped',+ 'terminal': {'available': false},+ };+ f.connection.failResume = scenario.fail;+ f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ c.select('offline');+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: ListenableBuilder(+ listenable: f.app,+ builder: (_, _) => SuperTabWorkspace(+ app: f.app,+ canvas: const Text('Native terminal'),+ onAddAgent: (_) {},+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final calls = f.connection.calls;+ // Participants → Open terminal, the only way to relaunch a stopped member.+ Future<void> openTerminal() async {+ tester+ .widget<SuperTabView>(find.byType(SuperTabView))+ .onOpenTerminal(c.snapshot!.agents.single);+ await tester.pumpAndSettle();+ }++ if (!scenario.viewer) {+ // A restored or revisited selection never undoes an explicit stop.+ c.selectTerminal('offline', 'worker');+ await tester.pumpAndSettle();+ expect(calls.where((call) => call.$1 == 'agent_resume'), isEmpty);+ expect(c.terminalAgent('offline'), isNull);+ expect(f.app.activeSwarm.panes, isEmpty);+ }+ await openTerminal();+ expect(calls.where((call) => call.$1 == 'agent_create'), isEmpty);+ expect(+ calls.where((call) => call.$1 == 'agent_resume'),+ hasLength(scenario.viewer ? 0 : 1),+ );+ if (scenario.fail) {+ expect(c.terminalAgent('offline'), isNull);+ expect(+ calls.where((call) => call.$2['action'] == 'prepareNative'),+ isEmpty,+ );+ // A failed resume leaves no native context behind on the backend.+ expect(+ calls.where(+ (call) => (call.$2['path'] as String?)?.endsWith('/native') == true,+ ),+ isEmpty,+ );+ expect(find.textContaining('did not come back'), findsOneWidget);+ } else {+ expect(f.app.activeSwarm.panes.single.agentId, 'native-worker');+ expect(+ f.app.stateOf('m')!.agents.single.sessionId,+ 'saved-multiply-conversation',+ );+ expect(f.app.stateOf('m')!.agents.single.isStopped, scenario.viewer);+ if (!scenario.viewer) {+ expect(+ calls.indexWhere((call) => call.$1 == 'agent_resume'),+ lessThan(+ calls.indexWhere((call) => call.$2['action'] == 'prepareNative'),+ ),+ );+ await f.app.requestClosePane(f.app.activeSwarm.panes.single.id);+ await tester.pumpAndSettle();+ await openTerminal();+ expect(+ calls.where((call) => call.$1 == 'agent_resume'),+ hasLength(1),+ );+ expect(calls.where((call) => call.$1 == 'agent_close'), isEmpty);+ }+ }+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ });+ }+testWidgets('each group restores its terminal and closing it never stops the agent',(tester) async {@@ -84,7 +203,7 @@ void main() {await tester.pumpAndSettle();expect(f.app.activeSwarm.panes.single.watchOnly, isFalse);// Native pane Close and the narrow Back action have the same personal state.- await f.app.closePane(f.app.activeSwarm.panes.single.id);+ await f.app.requestClosePane(f.app.activeSwarm.panes.single.id);await tester.pumpAndSettle();await c.refresh();await tester.pumpAndSettle();