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
A harness an agent starts opens beside it, marked with who started it (#1217)
Dee4db5e00bea12
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.tsindex 3eb4f3449..1ec9e5571 100644--- a/cli/e2e/agentClient.e2e.ts+++ b/cli/e2e/agentClient.e2e.ts@@ -133,6 +133,11 @@ describe('Harness for agents, end to end', () => {expect(sent.code, sent.out + sent.err).toBe(1)expect(sent.err).toContain(off)const kid = ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents).find((a) => a.name === 'kid')!+ // The windows open it beside the harness that started it, and say so in its header: its frame names that harness,+ // in the list and in the push a window first sees it by (desktop `Agent.parentAgentId`). The person's has none.+ expect(kid.parentAgentId).toBe(lead.id)+ expect(lead.parentAgentId).toBeNull()+ expect(client.frames.some((f) => f.type === 'agent_synced' && f.payload?.agent?.id === kid.id && f.payload.agent.parentAgentId === lead.id)).toBe(true)const back = await harness(d, String(kid.tmuxPane), ['send', 'lead', 'Footer checked.'])expect(back.code, back.out + back.err).toBe(1)expect(back.err).toContain(off)@@ -151,6 +156,16 @@ describe('Harness for agents, end to end', () => {expect(closed.out.trim()).toBe('Closed kid. Its conversation is kept.')const after = await run('ps', '--all', '--json')expect(JSON.parse(after.out).harnesses).toEqual(expect.arrayContaining([expect.objectContaining({ name: 'kid', state: 'stopped', startedBy: 'you' })]))++ // The same through `harness mcp` run in its pane (`harness_start`), as Claude Code with the plugin does.+ const server = mcp(d, { TMUX_PANE: String(lead.tmuxPane) })+ await server.request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'claude-code', version: '1' } })+ server.notify('notifications/initialized')+ const viaMcp = await server.call('harness_start', { task: 'hello from the pane', project: 'pane-kid', name: 'panekid' })+ expect(viaMcp.isError, viaMcp.text).toBe(false)+ const paneKid = ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents).find((a) => a.name === 'panekid')+ expect(paneKid?.parentAgentId).toBe(lead.id)+ server.close()client.close()})@@ -202,6 +217,9 @@ describe('Harness for agents, end to end', () => {expect(started.out).not.toContain('harness send')const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line))expect(ledger).toEqual([expect.objectContaining({ depth: 1, by: expect.objectContaining({ agentId: 'claude-code:outside-session', name: 'Claude Code' }), child: expect.objectContaining({ name: 'helper' }) })])+ // No harness started it, so no window has one to open it beside.+ const helper = ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents).find((a) => a.name === 'helper')+ expect(helper).toMatchObject({ parentAgentId: null })const waited = await run('wait', 'helper', '--timeout', '2m')expect(waited.code, waited.out + waited.err).toBe(0)diff --git a/cli/src/agentClient/commands.spec.ts b/cli/src/agentClient/commands.spec.tsindex 24762cb22..5a9ef3b04 100644--- a/cli/src/agentClient/commands.spec.ts+++ b/cli/src/agentClient/commands.spec.ts@@ -580,6 +580,14 @@ describe('harness new, run by an agent', () => {await expect((await agentOrigin(harness(d).deps))!.check()).resolves.toBeUndefined()})+ it('names its own harness as the one that started the new one; an agent outside Harness names none', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ expect((await agentOrigin(harness(d).deps))!.parentAgentId).toBe('lead')+ const outside = (await agentOrigin(harness(d, { pane: undefined, env: { CODEX_THREAD_ID: 't' } }).deps))!+ expect(outside).not.toHaveProperty('parentAgentId')+ })+it('refuses from what is left of an agent whose harness is gone', async () => {const origin = (await agentOrigin(harness(new FakeDaemon(), { pane: '%gone', where: () => ({ ...where, harnessPane: true }) }).deps))!await expect(origin.check()).rejects.toThrow(/no longer running/)diff --git a/cli/src/agentClient/commands.ts b/cli/src/agentClient/commands.tsindex 93d7a598a..9d2ba143a 100644--- a/cli/src/agentClient/commands.ts+++ b/cli/src/agentClient/commands.ts@@ -576,6 +576,8 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesR// The person's say, on the machine the agent runs on (Settings ▸ Agents, `harness settings`).if (!readAgentSettings(o.where.dataDir).agentsStartAgents) return refusing('TURNED_OFF', AGENTS_START_AGENTS_OFF)return {+ // A harness in a pane here: the new one is opened beside it in the windows. An agent outside Harness has no pane.+ ...(caller.outside ? {} : { parentAgentId: caller.agentId }),check: async () => {const refusal = spawnRefusal(caller, await liveFor(s, o, caller), o.ledger, o.where.machineId, s.now())if (refusal) throw new AgentClientError('SPAWN_LIMIT', refusal)diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex ff99caeb0..581813cdc 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -168,6 +168,9 @@ export class BackendSocket {/** `agent` when another agent started it (`harness new` from its pane); absent for the person. Kept on the* row: every launch of it adds a line to the pull requests it opens (lib/agentAttribution.ts). */startedBy?: StartedBy | null+ /** The harness here whose agent started it, when one in a Harness pane did (registry `parentAgentId`); only with+ * `startedBy: 'agent'`. The windows open the new harness beside it and say who started it. */+ parentAgentId?: string | null}) =>Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null/** Called on `remote_terminal_handoff` — cli.ts names the agent whose tile is that tmux pane, or null. */diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 7ac495341..52fbcc25e 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -641,14 +641,14 @@ describe('creating an agent', () => {it('started by another agent: its pull request line after every other argument, and who started it on the row', async () => {const { create } = setup()const cwd = folder()- await create(request({ cwd, agent: 'reviewer', startedBy: 'agent' }))+ await create(request({ cwd, agent: 'reviewer', startedBy: 'agent', parentAgentId: 'lead-1' }))expect(vi.mocked(agentLaunchArgs)).toHaveBeenCalledWith('claude', 'agent', { cwd, profile: null, environment: undefined })expect((vi.mocked(buildEngineLaunchArgv).mock.calls[0][1] as Record<string, unknown>).extraArgs).toEqual(['--agent', 'reviewer', '--settings', '{"attribution":{}}'])- expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ startedBy: 'agent' })+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ startedBy: 'agent', parentAgentId: 'lead-1' })// The person's: no line, and nothing recorded.await create(request())expect((vi.mocked(buildEngineLaunchArgv).mock.calls[1][1] as Record<string, unknown>).extraArgs).toBeUndefined()- expect(vi.mocked(createAndRegisterPane).mock.calls[1][0]).toMatchObject({ startedBy: null })+ expect(vi.mocked(createAndRegisterPane).mock.calls[1][0]).toMatchObject({ startedBy: null, parentAgentId: null })})diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex 010ba4fab..62ed42b11 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -99,7 +99,7 @@ export function createAgentCreator({if (input.resumeSessionId) return { ok: true, dispatch: () => externalResume(input) }const stale = () => ({ ok: false as const, error: 'LAUNCH_AUTHORITY_CHANGED', unavailable: 'launch', detail: 'Waiting for the original launch request’s authority.' })if (!authority.current()) return stale()- let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord, startedBy } = input+ let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord, startedBy, parentAgentId } = inputif (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }if (blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }const workspaceIdentity = () => { const info = statSync(cwd); return `${info.dev}:${info.ino}:${realpathSync(cwd)}` }@@ -375,6 +375,7 @@ export function createAgentCreator({defaultName: name,label: dshLabel,startedBy: startedBy ?? null,+ parentAgentId: parentAgentId ?? null,})if (!result.ok) return { ok: false, error: result.error, detail: result.detail }const { spawned, pending } = resultdiff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex 935f7e15d..b757e18b2 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -318,6 +318,11 @@ describe('agent_create, refused before any pane exists', () => {const refused = { error: 'INVALID_STARTED_BY', detail: 'startedBy is agent, or absent for the person' }expect(await ask({ engine: 'claude', cwd: '/w', startedBy: 'person' })).toStrictEqual(refused)expect(await ask({ engine: 'claude', cwd: '/w', startedBy: true })).toStrictEqual(refused)+ // Which harness started it: an agent id, and only beside startedBy agent.+ const noParent = { error: 'INVALID_STARTED_BY', detail: 'parentAgentId is the agent id of the harness that started it, with startedBy agent' }+ expect(await ask({ engine: 'claude', cwd: '/w', parentAgentId: 'a1' })).toStrictEqual(noParent)+ expect(await ask({ engine: 'claude', cwd: '/w', startedBy: 'agent', parentAgentId: '../a1' })).toStrictEqual(noParent)+ expect(await ask({ engine: 'claude', cwd: '/w', startedBy: 'agent', parentAgentId: 7 })).toStrictEqual(noParent)expect(create).not.toHaveBeenCalled()})})@@ -344,6 +349,18 @@ describe('agent_create, launched', () => {expect(Object.keys(byPerson!)).not.toContain('startedBy')})+ it('hands on which harness here started it, and leaves out one this machine does not know', async () => {+ const { ask, create } = setup()+ await ask({ engine: 'claude', cwd: '/w', startedBy: 'agent', parentAgentId: 'a1' })+ // Closed and forgotten while it ran `harness new`: its child still starts, beside nothing.+ await ask({ engine: 'claude', cwd: '/w', startedBy: 'agent', parentAgentId: 'gone' })+ await ask({ engine: 'claude', cwd: '/w', startedBy: 'agent', parentAgentId: null })+ const [known, unknown, none] = vi.mocked(create!).mock.calls.map(([input]) => input)+ expect(known).toMatchObject({ startedBy: 'agent', parentAgentId: 'a1' })+ expect(Object.keys(unknown!)).not.toContain('parentAgentId')+ expect(Object.keys(none!)).not.toContain('parentAgentId')+ })+it('opens a terminal in the home folder, bypasses permission unless told not to, and takes blank choices as none', async () => {const { ask, create } = setup()vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'absent' } as never).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex c273a4e74..0f952be69 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -29,7 +29,7 @@ import { parseGridLaunchOverride, type GridLaunchOverride } from '../../lib/gridimport { parseNewAgentModel, type NewAgentModel } from '../../lib/newAgentModel.js'import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError, type ProjectFolder } from '../../lib/projectFolder.js'import type { ScmLaunchRecord } from '../../scm/types.js'-import type { RegisteredSession } from '../../lib/registry.js'+import { parentAgentIdOf, type RegisteredSession } from '../../lib/registry.js'import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'import type { LaunchAuthority, LaunchPreparation } from '../../lib/launchPreparation.js'import { createPendingLaunches } from './pendingLaunches.js'@@ -379,6 +379,15 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, preif (payload.startedBy !== undefined && payload.startedBy !== null && payload.startedBy !== 'agent') {reply({ error: 'INVALID_STARTED_BY', detail: 'startedBy is agent, or absent for the person' }); return}+ // Which harness here that agent is (`harness new` or `harness_start` from its pane): the windows open the new one+ // beside it and say who started it. Only with `startedBy: 'agent'`, and only an agent id; one this machine does not+ // know is left out rather than refused, so a harness that just closed does not stop its child from starting.+ let parentAgentId: string | null = null+ if (payload.parentAgentId !== undefined && payload.parentAgentId !== null) {+ parentAgentId = payload.startedBy === 'agent' ? parentAgentIdOf(payload.parentAgentId) : null+ if (!parentAgentId) { reply({ error: 'INVALID_STARTED_BY', detail: 'parentAgentId is the agent id of the harness that started it, with startedBy agent' }); return }+ if (!byAgent(parentAgentId)) parentAgentId = null+ }const input = {engine,cwd: typeof cwd === 'string' ? cwd : terminal ? homedir() : '',@@ -395,6 +404,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pretakeOver,// Only when set: a person's create keeps the fingerprint its receipt was recorded with before the field....(payload.startedBy === 'agent' ? { startedBy: 'agent' as const } : {}),+ ...(parentAgentId ? { parentAgentId } : {}),}const fingerprintInput = model.state === 'ok' ? { ...input, modelSelection: model.selection } : inputif (creationId !== undefined) {diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.tsindex 813f48d2d..e3dd951d6 100644--- a/cli/src/lib/agentFrame.spec.ts+++ b/cli/src/lib/agentFrame.spec.ts@@ -70,6 +70,14 @@ describe('agentFrame', () => {expect(JSON.stringify(frame)).not.toContain('p-sess')})+ it('names the harness here that started it, and says null, never nothing, for every other', async () => {+ const row = session(null)+ expect(await agentFrame(row, { selectedModel: null, terminalAvailable: true })).toHaveProperty('parentAgentId', null)+ row.startedBy = 'agent'+ row.parentAgentId = 'lead-1'+ expect((await agentFrame(row, { selectedModel: null, terminalAvailable: true })).parentAgentId).toBe('lead-1')+ })+// The SCM seam (scm/scmProjects.ts) names the project's SCM and changes nothing else on it: every// field a client reads is exactly what agentProject reports. A folder no SCM claims is `none`.it('names the project\'s SCM beside exactly what agentProject reports, and none outside any repository', async () => {diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex 78e23a854..25e4e98f4 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -103,6 +103,13 @@ export type AgentFrame = {verdict: DshVerdict | null/** The agent this one was forked from (`agent_fork`), or null — a real answer, like `dsh: null`. */forkedFrom: { agentId: string; name: string } | null+ /**+ * The harness on this machine whose agent started this one (`harness new` or `harness_start` from its pane), by its+ * agent id, or null: the person, an agent outside Harness, or one on another machine. A window that shows that+ * harness in a tab opens this one beside it when it first sees it live, and its header says "started by" with the+ * starter's current name (desktop `Agent.parentAgentId`).+ */+ parentAgentId: string | null/** Whether `agent_fork` can do anything for this engine (lib/forkAgent.ts) — natively, or by a* handoff. A client hides the Fork action on a false rather than offering a button that refuses. */forkable: boolean@@ -256,6 +263,7 @@ export async function agentFrame(viewerName: dsh?.viewerName ?? null,verdict: dsh?.verdict ?? null,forkedFrom: s.forkedFrom ? { agentId: s.forkedFrom.agentId, name: s.forkedFrom.name } : null,+ parentAgentId: s.parentAgentId ?? null,forkable: engineCanFork(s.engine),resumeMode: resumeMode(s.engine),permissionMode: s.permissionMode ?? null,diff --git a/cli/src/lib/createAgentPane.spec.ts b/cli/src/lib/createAgentPane.spec.tsindex 5819da232..954e4005f 100644--- a/cli/src/lib/createAgentPane.spec.ts+++ b/cli/src/lib/createAgentPane.spec.ts@@ -127,6 +127,21 @@ describe('createAndRegisterPane', () => {expect(registry.byAgent(result.pending.agentId)).toMatchObject({ agent: 'harness-compute' })})+ it('records which harness here started it, only when another agent did', async () => {+ const { registry } = await loadRegistryModule()+ registry.load()+ const started = await createAndRegisterPane({+ tmuxBackend: fakeTmux([succeeded('%1')]), registry, engine: 'claude', cwd: '/tmp/demo', sessionLabel: 'harness-claude-1',+ argv: ['claude'], startedBy: 'agent', parentAgentId: 'lead-1',+ })+ expect(started.ok && started.pending).toMatchObject({ startedBy: 'agent', parentAgentId: 'lead-1' })+ const person = await createAndRegisterPane({+ tmuxBackend: fakeTmux([succeeded('%2')]), registry, engine: 'claude', cwd: '/tmp/demo', sessionLabel: 'harness-claude-2',+ argv: ['claude'], parentAgentId: 'lead-1',+ })+ expect(person.ok && person.pending).not.toHaveProperty('parentAgentId')+ })+it('does not retry a tmux spawn failure', async () => {const { registry } = await loadRegistryModule()registry.load()diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.tsindex 23045beab..7d7b93ce7 100644--- a/cli/src/lib/createAgentPane.ts+++ b/cli/src/lib/createAgentPane.ts@@ -46,6 +46,7 @@ export interface CreateAgentPaneDeps {forkedFrom?: ForkOrigin | nullexternalResume?: ExternalResumeIntentstartedBy?: StartedBy | null+ parentAgentId?: string | null}) => RegisteredSession | null }nativeToken?: stringengine: AgentEngine@@ -83,6 +84,8 @@ export interface CreateAgentPaneDeps {/** `agent` when another agent started it, recorded on the row so every relaunch keeps its pull request line* (lib/agentAttribution.ts). Already in `argv`: this is the record, not the launch. */startedBy?: StartedBy | null+ /** The harness here whose agent started it (registry.ts `parentAgentId`), recorded on the row; null otherwise. */+ parentAgentId?: string | nullexternalResume?: ExternalResumeIntent/** Rechecked by the backend after its gates and immediately before process dispatch. */current?: () => boolean@@ -134,6 +137,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<forkedFrom: deps.forkedFrom,...(deps.externalResume ? { externalResume: deps.externalResume } : {}),...(deps.startedBy ? { startedBy: deps.startedBy } : {}),+ ...(deps.startedBy && deps.parentAgentId ? { parentAgentId: deps.parentAgentId } : {}),})if (pending) return { ok: true, spawned, pending }console.warn(`[agent] create ${deps.engine} registration failed · pane ${spawned.runtime.paneId} · `diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.tsindex 483d289ce..123bac29c 100644--- a/cli/src/lib/newCommand.spec.ts+++ b/cli/src/lib/newCommand.spec.ts@@ -378,6 +378,32 @@ describe('harness new: the daemon', () => {expect(atTerminal.sent[1]!.payload).not.toHaveProperty('startedBy')})+ it('run by a harness here: names it as the one that started the new harness, so the windows open it beside it', async () => {+ const origin = {+ check: async () => {}, prompt: (text: string) => text, created: async () => null, next: () => '', parentAgentId: 'lead-agent',+ }+ const created = (id: string) => new FakeSocket((frame) => frame.type === 'fs_list_dir' ? { path: '/Users/mini', entries: [] }+ : frame.type === 'agent_create' ? { state: 'created', agent: { id, name: id } } : null)+ const here = created('kid')+ expect(await newCommand(deps(['codex', '--', 'review it'], here, { origin: async () => origin }))).toBe(0)+ expect(here.sent[1]!.payload).toMatchObject({ startedBy: 'agent', parentAgentId: 'lead-agent' })+ // `@this computer` is still here.+ const named = created('kid2')+ expect(await newCommand(deps(['codex', '@MacBook', '--', 'go'], named, { origin: async () => origin }))).toBe(0)+ expect(named.sent.find((frame) => frame.type === 'agent_create')!.payload.parentAgentId).toBe('lead-agent')+ // Another machine has no harness by that id: it records only that an agent started it.+ const far = created('far')+ expect(await newCommand(deps(['codex', '@mini', '~/w', '--', 'go'], far, { origin: async () => origin }))).toBe(0)+ const farCreate = far.sent.find((frame) => frame.type === 'agent_create')!.payload+ expect(farCreate.startedBy).toBe('agent')+ expect(farCreate).not.toHaveProperty('parentAgentId')+ // An agent outside Harness has no harness to name.+ const outside = created('helper')+ expect(await newCommand(deps(['codex', '--', 'go'], outside, { origin: async () => ({ ...origin, parentAgentId: undefined }) }))).toBe(0)+ expect(outside.sent[1]!.payload.startedBy).toBe('agent')+ expect(outside.sent[1]!.payload).not.toHaveProperty('parentAgentId')+ })+it('turns the machine\'s refusal into words, and a usage slip into the usage', async () => {const socket = new FakeSocket((frame) => frame.type === 'agent_create' ? { error: 'INVALID_CWD', detail: '/nope' } : null)const d = deps(['codex', '/nope'], socket)diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.tsindex 0206542ff..c72183f70 100644--- a/cli/src/lib/newCommand.ts+++ b/cli/src/lib/newCommand.ts@@ -255,6 +255,9 @@ export interface NewOrigin {created(machineId: string, agent: Record<string, unknown>): Promise<string | null>/** How to read, wait for and message what was started. */next(agent: Record<string, unknown>): string+ /** The caller's own harness, by agent id, when it is one on this computer: a harness started here records it, and the+ * windows open it beside the caller's pane. Absent for an agent outside Harness. */+ parentAgentId?: string}const ERRORS: Record<string, string> = {@@ -459,7 +462,11 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {}const asked = origin && args.prompt ? { ...args, prompt: origin.prompt(args.prompt, machineId) } : args// Started by an agent: the machine records it, and the pull requests it opens say so (lib/agentAttribution.ts).- const payload: Record<string, unknown> = { ...newAgentPayload(asked, cwd, baseEngine), ...(origin ? { startedBy: 'agent' } : {}) }+ // Started by a harness on this computer: which one, so the windows open it beside that harness.+ const parent = origin && local ? origin.parentAgentId ?? null : null+ const payload: Record<string, unknown> = {+ ...newAgentPayload(asked, cwd, baseEngine), ...(origin ? { startedBy: 'agent' } : {}), ...(parent ? { parentAgentId: parent } : {}),+ }let result = await session.request('agent_create', payload)// A launch the daemon holds (a native launch waiting its turn) is still on its way: asked after until it is not,// for a minute. Given up on at once, it could start later with an agent's task and no record of who started itdiff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex 8e69b509f..ef536a497 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -2280,6 +2280,46 @@ describe('who started it', () => {expect(registry.byAgent(pending.agentId)?.startedBy).toBe('agent')})+ it('keeps which harness here started it, beside startedBy, through a reload and the hook that rebuilds the row', async () => {+ const transcriptPath = join(dataDir, 'session-child.jsonl')+ writeFileSync(transcriptPath, '{}\n')+ const { registry, strictPersistedRow } = await loadRegistryModule()+ registry.load()+ const child = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/w', startedBy: 'agent', parentAgentId: 'lead-1' })!+ expect(child.parentAgentId).toBe('lead-1')+ // Only beside startedBy: the person's harness has no starter, and neither has a malformed id.+ expect(registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/w', parentAgentId: 'lead-1' })).not.toHaveProperty('parentAgentId')+ expect(registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%11' }], cwd: '/tmp/w', startedBy: 'agent', parentAgentId: '../x' })).not.toHaveProperty('parentAgentId')+ const row = JSON.parse(JSON.stringify(child))+ expect(strictPersistedRow(row)?.parentAgentId).toBe('lead-1')+ expect(strictPersistedRow({ ...row, startedBy: undefined })).not.toHaveProperty('parentAgentId')+ expect(strictPersistedRow({ ...row, parentAgentId: 7 })).not.toHaveProperty('parentAgentId')+ const bound = registry.register({ sessionId: 'session-child', transcriptPath, tmuxPane: '%9', cwd: '/tmp/w' })+ expect(bound?.entry.agentId).toBe(child.agentId)+ expect(bound?.entry.parentAgentId).toBe('lead-1')+ const { registry: reloaded } = await loadRegistryModule()+ reloaded.load()+ expect(reloaded.byAgent(child.agentId)?.parentAgentId).toBe('lead-1')+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ ...row, parentAgentId: 'a b' }]), { mode: 0o600 })+ const { registry: edited } = await loadRegistryModule()+ edited.load()+ expect(edited.byAgent(child.agentId)).toBeTruthy()+ expect(edited.byAgent(child.agentId)).not.toHaveProperty('parentAgentId')+ })++ it('does not hand who started it to the shell its engine leaves behind under a new id', async () => {+ const { registry } = await loadRegistryModule()+ registry.load()+ const child = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%12' }], cwd: '/tmp/w', startedBy: 'agent', parentAgentId: 'lead-1' })!+ // A new id with a starter is a new child to every window: it would open the person's shell beside the agent.+ const shell = registry.releaseEngine(child.agentId, true)!+ expect(shell.agentId).not.toBe(child.agentId)+ expect(shell).not.toHaveProperty('parentAgentId')+ // The same pane under its own id keeps it: that is still the harness the agent started.+ const kept = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%13' }], cwd: '/tmp/w', startedBy: 'agent', parentAgentId: 'lead-1' })!+ expect(registry.releaseEngine(kept.agentId)).toMatchObject({ agentId: kept.agentId, parentAgentId: 'lead-1' })+ })+it('drops anything but another agent from a hand-edited row', async () => {const { registry, strictPersistedRow } = await loadRegistryModule()registry.load()diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 2970e6090..7c270e8dd 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -246,6 +246,13 @@ export interface RegisteredSession {* engine add a line to the pull requests it opens (lib/agentAttribution.ts). Never re-derived from the process.*/startedBy?: StartedBy+ /**+ * The harness on this machine whose agent started this one (`harness new`, or `harness_start` through `harness mcp`,+ * run in its pane), by agent id. Absent when the person started it, and when the agent that did is outside Harness or+ * on another machine. Recorded once at creation beside `startedBy` and carried like it, so every window can put the+ * new harness beside the one that started it and say so in its header (docs/design/2026-10-11-agent-client.md).+ */+ parentAgentId?: string/** Legacy launcher-owned snapshots may still contain this field. New records never write it. */launcherId?: stringtranscriptPath: string | null@@ -614,7 +621,7 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {// Taken out of the spread and put back only when it is a real moment: the spread would otherwise// carry a hand-edited string or a negative number straight into the frame's `toISOString()`.// `forkedFrom` is out too, so an invalid one is dropped rather than spread back in as-is.- const { identityHold: _identityHold, evidenceRevision: _revision, interpretationHold: _interpretation, admissionHold: _admission, lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, externalResume: _externalResume, startedBy: rawStartedBy, ...rest } = row+ const { identityHold: _identityHold, evidenceRevision: _revision, interpretationHold: _interpretation, admissionHold: _admission, lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, externalResume: _externalResume, startedBy: rawStartedBy, parentAgentId: rawParentAgentId, ...rest } = rowconst lastOpenedAt = normalizedOpenedAt(rawOpenedAt)// Out of the spread for the same reason: a half-formed record is dropped, never relaunched with.const scmLaunch = parseScmLaunchRecord(rawScmLaunch)@@ -637,6 +644,7 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {...normalizedForkedFrom(rawForkedFrom),// Out of the spread too: only `agent` is a harness another agent started; anything else is the person's....(rawStartedBy === 'agent' ? { startedBy: 'agent' as const } : {}),+ ...normalizedParent(rawStartedBy, rawParentAgentId),cwd: typeof row.cwd === 'string' ? row.cwd : null,runtimes,primaryRuntimeKey: normalizedPrimary,@@ -655,6 +663,20 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {}}+/**+ * An agent id as a harness that started another is named by (`parentAgentId`): one word, never a path. The registry's+ * own ids are uuids; the bound only keeps a hand-edited row from carrying anything else into every frame.+ */+export function parentAgentIdOf(value: unknown): string | null {+ return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value) ? value : null+}++/** `parentAgentId` as a row keeps it: only beside `startedBy: 'agent'`, and only an agent id. */+function normalizedParent(startedBy: unknown, value: unknown): { parentAgentId: string } | Record<string, never> {+ const parentAgentId = startedBy === 'agent' ? parentAgentIdOf(value) : null+ return parentAgentId ? { parentAgentId } : {}+}+/*** Where a fork came from. `sessionId` / `transcriptPath` are the PARENT's conversation at the moment of the* fork; they let a fork that has not started its own conversation yet still say whose history it carries.@@ -1299,6 +1321,7 @@ class Registry {...(permissionModeName(raw.permissionMode) ? { permissionMode: raw.permissionMode } : {}),...(raw.terminalHost === true || engine === 'terminal' ? { terminalHost: true } : {}),...(raw.startedBy === 'agent' ? { startedBy: 'agent' as const } : {}),+ ...normalizedParent(raw.startedBy, raw.parentAgentId),transcriptPath,defaultName: normalizedDefaultName(raw.defaultName),title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),@@ -1604,6 +1627,8 @@ class Registry {externalResume?: ExternalResumeIntent/** Who started it — see RegisteredSession.startedBy. */startedBy?: StartedBy | null+ /** The harness here that started it — see RegisteredSession.parentAgentId. Kept only with `startedBy: 'agent'`. */+ parentAgentId?: string | null}): RegisteredSession | null {if (this.writeBlocked) return nullconst externalResume = input.externalResume === undefined ? undefined : parseExternalResume(input.externalResume)@@ -1641,6 +1666,7 @@ class Registry {...(isTerminalEngine(input.engine) ? { terminalHost: true } : {}),...normalizedForkedFrom(input.forkedFrom),...(input.startedBy === 'agent' ? { startedBy: 'agent' as const } : {}),+ ...normalizedParent(input.startedBy, input.parentAgentId),transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,@@ -1986,6 +2012,8 @@ class Registry {// Carried forward like `agent`: dropped at the first hook, a restart of a harness another agent started came// back without its pull request line (found by e2e/agentClient.e2e.ts)....(existing?.startedBy ? { startedBy: existing.startedBy } : {}),+ // And who it was, for the same reason: dropped at the first hook, the windows lost which harness started it.+ ...(existing?.parentAgentId ? { parentAgentId: existing.parentAgentId } : {}),...(existing?.bypassPermission ? { bypassPermission: true } : {}),...(existing?.permissionMode ? { permissionMode: existing.permissionMode } : {}),...(existing?.resumeOnly ? { resumeOnly: true, launch: { state: 'ready' as const } } : {}),@@ -2136,6 +2164,9 @@ class Registry {// The archived conversation owns the original Harness ID. Preserve the physical shell under// a new identity, without sending input, stopping processes or claiming its route twice.const entry = separateShell ? { ...original, agentId: randomUUID(), dsh: null, dshRuntime: null, agent: null, defaultName: this.automaticName('Terminal', new Date()) } : original+ // The shell under a new identity is the person's, not a harness an agent started: kept, a window took the new id for+ // a new child and opened the shell beside the agent, even after the person had closed the child (review of #1217).+ if (separateShell) delete entry.parentAgentIdthis.releaseBinding(entry)delete entry.resumeOnlydelete entry.externalResumediff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 9ce00cf10..425a53205 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -96,6 +96,7 @@ import 'machine_profile.dart';import 'pane_layout_store.dart';import 'terminal_pane.dart';import 'device_visit.dart';+import 'started_children.dart';import 'swarm.dart';import '../terminal/terminal_binary.dart';import '../update/desktop_updater.dart';@@ -369,6 +370,12 @@ class MachineState {/// Moves with every change of [agents]: a list read before one is older than it/// ([AppNotifier._syncAgentsIfChanged]).int agentsRevision = 0;++ /// Whether this window has read the machine's whole list once. What was in+ /// it, or pushed before it, was there when the window came: a harness an+ /// agent started opens beside its starter only when it appears after+ /// (`AppNotifier._openStartedChild`), never on a restore.+ bool agentsListedOnce = false;AgentLoadStatus agentLoadStatus = AgentLoadStatus.idle;bool agentsRefreshing = false;String? agentsLoadError;@@ -7482,7 +7489,15 @@ class AppNotifier extends ChangeNotifier {.toList(),nameRevision,);- if (agentsEqual(machine.agents, agents)) return;+ if (agentsEqual(machine.agents, agents)) {+ // A whole list read, even one that changes nothing: what pushes+ // brought before it was the window's restore, and what comes after it+ // is new (`_openStartedChild`). Left unset when the first load failed+ // and pushes filled the list, no harness an agent started would ever+ // open beside it (review of #1217).+ machine.agentsListedOnce = true;+ return;+ }_replaceAgents(machine, agents);notifyListeners();} catch (_) {@@ -9990,6 +10005,8 @@ class AppNotifier extends ChangeNotifier {}void _replaceAgents(MachineState machine, List<Agent> agents) {+ final listedBefore = machine.agentsListedOnce;+ machine.agentsListedOnce = true;final previousWork = {for (final agent in machine.agents) agent.id: agent};agents = [for (final agent in agents)@@ -10065,6 +10082,11 @@ class AppNotifier extends ChangeNotifier {for (final agent in agents) {_syncViewerPane(machine, agent);}+ // A harness an agent started that this list brings for the first time:+ // beside its starter. Not from the first list, which is the restore.+ for (final agent in agents) {+ _openStartedChild(machine, agent, arrived: listedBefore);+ }}void _reconcileAgentActivity(@@ -13860,6 +13882,66 @@ class AppNotifier extends ChangeNotifier {revealAgentView(machineId, agentId);}+ /// Harnesses another harness's agent started that this window has already+ /// placed or passed over, by machine and agent id: each is decided once, the+ /// first time it is seen live, so a pane the person closes stays closed.+ final _decidedStartedChildren = <(String, String)>{};++ /// A harness an agent here started (`harness new`, or `harness_start`+ /// through `harness mcp`, from its pane) opens right beside that agent's+ /// pane, in the tab that shows it, without taking the focus or the terminal+ /// from anyone (owner, 2026-10-11; `state/started_children.dart`).+ ///+ /// Only one [arrived] after this window read the machine's list, and seen+ /// live: what the first list or a push before it brings is the window's+ /// restore, and is passed over for good. Never one this window has shown+ /// before ([hasOpenedHarness]): the person closed it. Where the starter is+ /// in no tab here nothing changes; it is in ⌘O as before.+ ///+ /// Every window that shows the starter does this, on every computer, and+ /// that is still one pane: each picks the same tab (the first in the desk's+ /// order that shows the starter), the desk's `pane.add` is idempotent per+ /// tab, machine and agent (`desk_sync.dart`), and a window that hears of the+ /// pane from the desk first finds the child already in a tab and leaves it.+ /// Placing it in the daemon instead would need the desk's layout rules+ /// there, and a signed-out computer has no desk at all.+ void _openStartedChild(+ MachineState machine,+ Agent child, {+ required bool arrived,+ }) {+ if (child.parentAgentId == null || machine.machine.isShared) return;+ final machineId = machine.machine.machineId;+ final key = (machineId, child.id);+ if (_decidedStartedChildren.contains(key)) return;+ if (arrived && !startedChildLive(child)) return;+ _decidedStartedChildren.add(key);+ if (_decidedStartedChildren.length > 4096) {+ _decidedStartedChildren.remove(_decidedStartedChildren.first);+ }+ if (!arrived || hasOpenedHarness(machineId, child.id)) return;+ final place = startedChildPlacement(+ tabs: swarms,+ machineId: machineId,+ child: child,+ now: DateTime.now(),+ maxPanes: maxPanes,+ );+ if (place == null) return;+ unawaited(+ assignAgentToPane(+ null,+ machineId,+ child.id,+ swarmId: place.tab.id,+ besidePaneId: place.parent.id,+ autoTile: true,+ focus: false,+ intent: AttachIntent.automatic,+ ),+ );+ }+/// Every tile on the machine, not just the focused one: the machine is what/// went away, so a tile of the same machine sitting in another corner of the/// grid is just as dead and must say so rather than keep showing a terminal@@ -14508,6 +14590,10 @@ class AppNotifier extends ChangeNotifier {/// touching this Mac, so the terminal they show must not be taken from/// whoever is typing in it.AttachIntent intent = AttachIntent.person,++ /// A new tile goes right after this one, where the tab reads it, rather+ /// than at the end: a harness another harness started opens beside it.+ int? besidePaneId,}) async {final target = swarms.where((s) => s.id == (swarmId ?? activeSwarmId))@@ -14556,9 +14642,23 @@ class AppNotifier extends ChangeNotifier {notifyListeners();return;}+ final beside = replaced == null && split == null && besidePaneId != null+ ? targetPanes.where((p) => p.id == besidePaneId).firstOrNull+ : null;+ if (beside != null) {+ // The tab's reading order first, as `Swarm.remove` does: the reflow+ // below lays the list out in order, and a split earlier in the tab's+ // life may have put the list out of step with what the person sees.+ final ordered = target.panesInReadingOrder;+ targetPanes+ ..clear()+ ..addAll(ordered);+ }final insertion = replaced == null? split == null- ? targetPanes.length+ ? beside == null+ ? targetPanes.length+ : targetPanes.indexOf(beside) + 1: split.paneIds.indexOf(split.paneId) + 1: targetPanes.indexOf(replaced);final pendingLayout =@@ -14593,6 +14693,12 @@ class AppNotifier extends ChangeNotifier {target.arranged = null;target.arrangedKey = null;}+ if (beside != null) {+ // Pins stay with their panes, wherever the new tile moved them.+ target.pinnedSlots.updateAll(+ (id, _) => targetPanes.indexWhere((p) => p.id == id),+ );+ }if (split != null) {target.pinnedSlots.updateAll((_, slot) => slot >= insertion ? slot + 1 : slot,@@ -17232,6 +17338,11 @@ class AppNotifier extends ChangeNotifier {try {final agent = Agent.fromJson(Map<String, dynamic>.from(raw));var changed = _upsertAgent(machine, agent);+ _openStartedChild(+ machine,+ agent,+ arrived: machine.agentsListedOnce,+ );if (agent.terminalAvailable) {// A pane created before this agent's terminal was verified is still sitting on// "Attaching…" with no session — nothing else re-checks it once agentLoadStatus is@@ -17265,6 +17376,11 @@ class AppNotifier extends ChangeNotifier {try {final agent = Agent.fromJson(Map<String, dynamic>.from(raw));_upsertAgent(machine, agent);+ _openStartedChild(+ machine,+ agent,+ arrived: machine.agentsListedOnce,+ );// Same reattach as `agent_synced` above — a pane can be waiting on this exact agent// (e.g. one this window's own New Agent dialog just opened) with no session yet._attachPendingPanes(machine, intent: AttachIntent.automatic);@@ -17522,6 +17638,10 @@ class AppNotifier extends ChangeNotifier {Future<void> restorePaneLayoutForTest({bool claimOnAttach = false}) =>_restorePaneLayout(claimOnAttach: claimOnAttach);+ @visibleForTesting+ Future<void> syncAgentsIfChangedForTest(String machineId) =>+ _syncAgentsIfChanged(machineStates[machineId]!);+@visibleForTestingFuture<void> handleMachineEventForTest(String machineId,diff --git a/desktop/lib/state/started_children.dart b/desktop/lib/state/started_children.dartnew file mode 100644index 000000000..e785f899b--- /dev/null+++ b/desktop/lib/state/started_children.dart@@ -0,0 +1,69 @@+/// A harness another harness's agent started opens beside it.+///+/// An agent in a Harness pane starts another harness with `harness new`, or+/// with `harness_start` through `harness mcp` run in that pane. The daemon+/// records which harness started it (the frame's `parentAgentId`, CLI+/// `registry.ts`), and a window that shows the starter in a tab opens the new+/// one in that tab, right beside it, so the person can watch, answer or stop it+/// (owner, 2026-10-11, mockup approved; docs/design/2026-10-11-agent-client.md,+/// "The person sees it"). Before this the child ran and answered and appeared+/// nowhere but the Harnesses count and ⌘O (a clean VM, CLI 0.3.75).+///+/// Only a child first seen live: never one restored with the window, one the+/// person already closed, or one that stopped. `AppNotifier` keeps what this+/// window has seen; this is the pure half, where it goes.+library;++import '../core/models.dart' show Agent;+import 'swarm.dart';+import 'terminal_pane.dart';++/// How long after it started a child still opens by itself. Long enough for a+/// launch the daemon held a while (a model waking, an engine being checked);+/// short enough that a laptop waking from a night's sleep does not fill a tab+/// with what its agents started while it was closed.+const startedChildFresh = Duration(minutes: 5);++/// Whether [child] is a harness started by another harness and running now:+/// what may open by itself.+bool startedChildLive(Agent child) =>+ child.parentAgentId != null &&+ child.parentAgentId != child.id &&+ !child.isStopped &&+ child.status != 'offline' &&+ child.terminalAvailable &&+ child.launchState != 'failed';++/// The tab [child] opens in and the pane it opens beside, or null: it is not+/// live, not new, already shown here, or its starter is in no tab here with+/// room for one more. A tab that is not for harnesses (the Store, an+/// orchestrator) never takes one.+///+/// Where the starter is in two tabs, the first in the row, never the one in+/// front: the row's order is the desk's, the same on every computer, and two+/// computers that each chose their own front tab would leave the child in both+/// (review of #1217).+({Swarm tab, TerminalPane parent})? startedChildPlacement({+ required Iterable<Swarm> tabs,+ required String machineId,+ required Agent child,+ required DateTime now,+ required int maxPanes,+}) {+ if (!startedChildLive(child)) return null;+ final created = child.createdAt;+ if (created == null || now.difference(created) > startedChildFresh) {+ return null;+ }+ TerminalPane? paneOf(Swarm tab, String agentId) => tab.panes+ .where((pane) => pane.machineId == machineId && pane.agentId == agentId)+ .firstOrNull;+ if (tabs.any((tab) => paneOf(tab, child.id) != null)) return null;+ bool takes(Swarm tab) =>+ tab.kind == 'harness' &&+ tab.panes.length < maxPanes &&+ paneOf(tab, child.parentAgentId!) != null;+ final tab = tabs.where(takes).firstOrNull;+ if (tab == null) return null;+ return (tab: tab, parent: paneOf(tab, child.parentAgentId!)!);+}diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 5b73a86e0..de41365a1 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -2481,6 +2481,15 @@ class _TerminalPanelState extends State<TerminalPanel>// equality, so a frame that changed nothing but the verdict must still// be seen as a change by the one field that can say so.verdict: agent?.verdict,+ // The header says who started it by that harness's name now. Renaming+ // the starter changes nothing in this agent's own frame, so its name is+ // a field of its own here, or the header kept the old one.+ startedBy: agent?.parentAgentId == null+ ? null+ : machine?.agents+ .where((a) => a.id == agent!.parentAgentId)+ .firstOrNull+ ?.displayName,project: agent == null ? null : machine?.projectOf(agent),compact: widget.compactHeader,close: widget.onClose != null,@@ -2723,8 +2732,18 @@ class _TerminalHeader extends StatelessWidget {.firstOrNull;final project = agent == null ? null : machine?.projectOf(agent);final machineName = machine?.machine.displayName ?? session.machineId;+ // 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.+ final startedBy = agent?.parentAgentId == null+ ? null+ : machine?.agents+ .where((a) => a.id == agent!.parentAgentId)+ .firstOrNull+ ?.displayName;final identityDetail = [session.agentName,+ if (startedBy != null) 'Started by $startedBy',machineName,if (project != null) project.cwd,?project?.branchDetail,@@ -3115,6 +3134,7 @@ class _TerminalHeader extends StatelessWidget {message: [if (forkedFrom != null)'Forked from ${forkedFrom.name}',+ if (startedBy != null) 'Started by $startedBy',if (project != null) project.cwd,?project?.branchDetail,machineName,@@ -3131,8 +3151,15 @@ class _TerminalHeader extends StatelessWidget {// Not a branch Harness made up that waits for the// session's name, nor a commit an agent checked out.branch: narrow ? null : project?.shownBranch,- leading: !narrow && forkedFrom != null+ // Then who started it: the one fact a+ // harness an agent opened beside it has+ // that its folder cannot tell.+ leading: narrow+ ? null+ : forkedFrom != null? 'forked from ${forkedFrom.name}'+ : startedBy != null+ ? 'started by $startedBy': null,),),diff --git a/desktop/test/started_child_pane_test.dart b/desktop/test/started_child_pane_test.dartnew file mode 100644index 000000000..0bb21f9be--- /dev/null+++ b/desktop/test/started_child_pane_test.dart@@ -0,0 +1,348 @@+// A harness another harness's agent started (`harness new`, `harness_start`+// from its pane) opens as a pane beside it, in the same tab, marked with who+// started it (owner, 2026-10-11; docs/design/2026-10-11-agent-client.md, "The+// person sees it"). Only one first seen live: never on a restore, never again+// after the person closed it, never a stopped one.+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/state/started_children.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/widgets/terminal_panel.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show MemoryStore, createApp;++/// The machine as the daemon answers it: its list, and nothing else asked of it.+class _Machine extends WsConn {+ _Machine()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ List<Map<String, dynamic>> listed = [_agent('a0', name: 'lead')];++ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}++ @override+ Future<void> connect() async {}++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async => type == 'agents_list' ? {'agents': listed} : {};+}++Map<String, dynamic> _agent(+ String id, {+ String? name,+ String? parent,+ DateTime? createdAt,+ String status = 'active',+}) => {+ 'id': id,+ 'name': name ?? id,+ 'engine': parent == null ? 'codex' : 'claude',+ 'status': status,+ 'createdAt': (createdAt ?? DateTime.now()).toUtc().toIso8601String(),+ 'terminal': {'available': true, 'primary': '', 'runtimes': []},+ 'parentAgentId': parent,+};++Future<void> _push(AppNotifier app, Map<String, dynamic> agent) =>+ app.handleMachineEventForTest('m', {+ 'type': 'agent_synced',+ 'payload': {'agent': agent},+ });++List<String?> _agents(Swarm tab) => tab.panes.map((p) => p.agentId).toList();++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ test('a harness its agent started opens right beside it, in its tab, and takes nothing from the person', () async {+ final machine = _Machine();+ final app = createApp(connectionForTest: (_) => machine, connected: true);+ addTearDown(app.dispose);+ machine.listed = [+ _agent('a0', name: 'lead'),+ _agent('a1', name: 'notes'),+ _agent('a2', name: 'elsewhere'),+ ];+ await app.reloadMachineData('m');+ await app.addAgentToSwarm('m', 'a0');+ await app.addAgentToSwarm('m', 'a1');+ final work = app.activeSwarm;+ app.newSwarm(name: 'Other');+ await app.addAgentToSwarm('m', 'a2');+ final other = app.activeSwarm;+ final focused = app.focusedPane;++ await _push(app, _agent('kid', name: 'python-opinion', parent: 'a0'));+ expect(_agents(work), ['a0', 'kid', 'a1']);+ // The person stays where they are: the tab in front, its focus.+ expect(app.activeSwarm, same(other));+ expect(app.focusedPane, same(focused));+ final kid = work.panes.singleWhere((p) => p.agentId == 'kid');+ expect(work.focusedPaneId, isNot(kid.id));++ // The next frames of it change nothing; it is one pane.+ await _push(app, _agent('kid', name: 'python-opinion', parent: 'a0'));+ expect(_agents(work), ['a0', 'kid', 'a1']);+ expect(app.allPanes.where((p) => p.agentId == 'kid'), hasLength(1));+ });++ test('where two tabs show the starter, the first in the row, the same on every computer', () async {+ final machine = _Machine();+ final app = createApp(connectionForTest: (_) => machine, connected: true);+ addTearDown(app.dispose);+ await app.reloadMachineData('m');+ await app.addAgentToSwarm('m', 'a0');+ final first = app.activeSwarm;+ app.newSwarm(name: 'Second');+ await app.addAgentToSwarm('m', 'a0');+ final second = app.activeSwarm;++ await _push(app, _agent('kid', parent: 'a0'));+ expect(_agents(first), ['a0', 'kid']);+ expect(_agents(second), ['a0']);+ expect(app.activeSwarm, same(second));+ });++ test('a list read after pushes filled it still counts as the window\'s first', () async {+ final machine = _Machine();+ final app = createApp(connectionForTest: (_) => machine, connected: true);+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ // The first load failed; pushes alone made the list, and the safety-net+ // read finds nothing to change.+ final lead = _agent('a0', name: 'lead', createdAt: DateTime.now());+ machine.listed = [lead];+ app.stateOf('m')!.agents = [];+ await _push(app, lead);+ await app.syncAgentsIfChangedForTest('m');+ expect(app.stateOf('m')!.agents, hasLength(1));+ await _push(app, _agent('kid', parent: 'a0'));+ expect(_agents(app.activeSwarm), ['a0', 'kid']);+ });++ test('a list that brings it first places it too, once the window has read one', () async {+ final machine = _Machine();+ final app = createApp(connectionForTest: (_) => machine, connected: true);+ addTearDown(app.dispose);+ await app.reloadMachineData('m');+ await app.addAgentToSwarm('m', 'a0');+ machine.listed = [...machine.listed, _agent('kid', parent: 'a0')];+ await app.reloadMachineData('m');+ expect(_agents(app.activeSwarm), ['a0', 'kid']);+ });++ test('not on restore: what the first list brings stays where it was', () async {+ final storage = MemoryStore();+ await PaneLayoutStore(storage: storage).saveSwarms([+ Swarm(id: 'work', name: 'Work')+ ..panes.add(TerminalPane(id: 1, machineId: 'm', agentId: 'a0')),+ ], 'work');+ final machine = _Machine()+ ..listed = [_agent('a0', name: 'lead'), _agent('kid', parent: 'a0')];+ final app = createApp(+ store: storage,+ connectionForTest: (_) => machine,+ );+ addTearDown(app.dispose);+ await app.restorePaneLayoutForTest();+ // A push before the window has read the list is the restore too.+ await _push(app, _agent('early', parent: 'a0'));+ await app.reloadMachineData('m');+ await _push(app, _agent('kid', parent: 'a0'));+ await _push(app, _agent('early', parent: 'a0'));+ expect(_agents(app.activeSwarm), ['a0']);+ expect(app.stateOf('m')!.agents.map((a) => a.id), contains('kid'));+ });++ test('not again after the person closes it', () async {+ final machine = _Machine();+ final app = createApp(connectionForTest: (_) => machine, connected: true);+ addTearDown(app.dispose);+ await app.reloadMachineData('m');+ await app.addAgentToSwarm('m', 'a0');+ await _push(app, _agent('kid', parent: 'a0'));+ expect(_agents(app.activeSwarm), ['a0', 'kid']);++ await app.closePane(app.paneOfAgent('m', 'kid')!.id);+ expect(_agents(app.activeSwarm), ['a0']);+ await _push(app, _agent('kid', name: 'renamed', parent: 'a0'));+ machine.listed = [...machine.listed, _agent('kid', parent: 'a0')];+ await app.reloadMachineData('m');+ // Stopped and started again, it is still the one the person closed.+ await app.handleMachineEventForTest('m', {+ 'type': 'agent_deleted',+ 'payload': {'agentId': 'kid'},+ });+ await _push(app, _agent('kid', parent: 'a0'));+ expect(_agents(app.activeSwarm), ['a0']);+ });++ test('nothing new for a stopped one, an old one, one whose starter is in no tab, or the person\'s own', () async {+ final machine = _Machine();+ final app = createApp(connectionForTest: (_) => machine, connected: true);+ addTearDown(app.dispose);+ await app.reloadMachineData('m');+ await app.addAgentToSwarm('m', 'a0');+ await _push(app, _agent('stopped', parent: 'a0', status: 'stopped'));+ await _push(+ app,+ _agent(+ 'old',+ parent: 'a0',+ createdAt: DateTime.now().subtract(const Duration(minutes: 30)),+ ),+ );+ await _push(app, _agent('orphan', parent: 'a9'));+ await _push(app, _agent('persons'));+ expect(_agents(app.activeSwarm), ['a0']);+ expect(+ app.stateOf('m')!.agents.map((a) => a.id),+ containsAll(['stopped', 'old', 'orphan', 'persons']),+ );+ });++ test('where it opens, decided from the tabs alone', () {+ final now = DateTime.utc(2026, 10, 11, 12);+ Agent child({String? parent = 'lead', DateTime? at}) => Agent(+ id: 'kid',+ name: 'kid',+ engine: 'claude',+ terminalAvailable: true,+ parentAgentId: parent,+ createdAt: at ?? now,+ );+ TerminalPane pane(int id, String agentId, {String machineId = 'm'}) =>+ TerminalPane(id: id, machineId: machineId, agentId: agentId);+ final store = Swarm(id: 'store', kind: 'store')..panes.add(pane(1, 'lead'));+ final full = Swarm(id: 'full')+ ..panes.addAll([pane(2, 'lead'), pane(3, 'x')]);+ final work = Swarm(id: 'work')..panes.add(pane(4, 'lead'));+ final elsewhere = Swarm(id: 'elsewhere')+ ..panes.add(pane(5, 'lead', machineId: 'other'));+ ({Swarm tab, TerminalPane parent})? place(+ Iterable<Swarm> tabs,+ Agent agent,+ ) => startedChildPlacement(+ tabs: tabs,+ machineId: 'm',+ child: agent,+ now: now,+ maxPanes: 2,+ );++ // Not a tab for harnesses, nor a full one: the next that shows it.+ expect(place([store, full, work], child())?.tab, same(work));+ expect(place([store, full, work], child())?.parent.id, 4);+ // The same agent id on another machine is another harness.+ expect(place([elsewhere], child()), isNull);+ expect(place([work], child(parent: null)), isNull);+ expect(+ place([work], child(at: now.subtract(const Duration(minutes: 6)))),+ isNull,+ );+ // A clock a little ahead on the child's machine is still now.+ expect(+ place([work], child(at: now.add(const Duration(minutes: 1))))?.tab,+ same(work),+ );+ // Already in a tab here (the desk brought it from another computer).+ final shown = Swarm(id: 'shown')+ ..panes.addAll([pane(6, 'lead'), pane(7, 'kid')]);+ expect(place([shown, work], child()), isNull);+ expect(startedChildLive(child()), isTrue);+ expect(+ startedChildLive(+ Agent(+ id: 'kid',+ name: 'kid',+ parentAgentId: 'lead',+ terminalAvailable: true,+ launchState: 'failed',+ ),+ ),+ isFalse,+ );+ });++ for (final brightness in Brightness.values) {+ testWidgets('its header says who started it, by that harness\'s name now '+ '(${brightness.name})', (tester) async {+ tester.view.physicalSize = const Size(1400, 600);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ app.stateOf('m')!.agents = [+ ...app.stateOf('m')!.agents,+ const Agent(+ id: 'kid',+ name: 'python-opinion',+ engine: 'claude',+ terminalAvailable: true,+ parentAgentId: 'a0',+ ),+ ];+ final session = TerminalSession(+ machineId: 'm',+ agentId: 'kid',+ agentName: 'python-opinion',+ engineId: 'claude',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ )..status = TerminalSessionStatus.controlling;+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ // The grid rebuilds its panes as the app changes; so does this.+ home: Scaffold(+ body: ListenableBuilder(+ listenable: app,+ builder: (context, _) => TerminalPanel(+ notifier: app,+ session: session,+ focused: false,+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ expect(+ find.textContaining('started by Agent 0', findRichText: true),+ findsOneWidget,+ );++ // Renamed since: the header follows.+ await app.handleMachineEventForTest('m', {+ 'type': 'agent_renamed',+ 'payload': {'agentId': 'a0', 'name': 'lead'},+ });+ await tester.pump();+ expect(+ find.textContaining('started by lead', findRichText: true),+ findsOneWidget,+ );+ session.dispose();+ });+ }+}diff --git a/docs/design/2026-10-11-agent-client.md b/docs/design/2026-10-11-agent-client.mdindex 4ae3e1a41..893e2c643 100644--- a/docs/design/2026-10-11-agent-client.md+++ b/docs/design/2026-10-11-agent-client.md@@ -103,9 +103,39 @@ limits, `close` and measurement read it.It is a file the CLI appends to, not a field in the core's registry, so this first version changes nothing in thecore and can be removed whole. Like Agent Messages it is a collaboration scope, not a sandbox: any process of the-same user can write it. If agents use this, the record moves into the registry beside `forkedFrom`, and the-windows can show it in the pane header. The registry keeps one fact of it already, for the pull request line below:-the row's `startedBy` is `agent`. Who, and the depth, stay in the file.+same user can write it. The registry keeps two facts of it: the row's `startedBy` is `agent`, for the pull request+line below, and, when the starter is a harness on the same machine, its agent id (`parentAgentId`, sent by `harness+new` with `agent_create`; one the machine does not know is left out). The depth, and starters outside Harness or on+another machine, stay in the file.++### The person sees it (October 11)++Found in a clean VM with CLI 0.3.75: a Codex harness asked for a second opinion from Claude Code ran `harness new+claude …`, and the child ran and answered but appeared nowhere in the app, only in the Harnesses count and ⌘O. The+owner chose, from a mockup: **the child opens as a pane in the same tab, beside the agent that started it, marked+with who started it.**++```+┌─ code ─────────────────────────────────────────┐+│┌ lead (Codex) ─────────┐┌ python-opinion ─────┐│+││ › get a second opinion││ started by lead ││+││ from claude code… ││ Claude Code · Opus ││+││ • Ran harness new ││ › Give your opinion ││+││ • Waiting… ││ • I recommend spaces││+│└───────────────────────┘└─────────────────────┘│+└────────────────────────────────────────────────┘+```++Every agent frame carries `parentAgentId` (null for the rest). A desktop window that first sees such a harness live,+after it has read that machine's list once, and shows its starter in a tab, adds it right after the starter in that+tab (the first in the row where two show it, so every computer picks the same one) without moving focus or taking the+terminal (`desktop/lib/state/started_children.dart`). Never what the first list brings (the window's restore), one the window+has shown before (the person closed it), a stopped one, or one started more than five minutes ago (a laptop waking).+The shell an exited engine leaves under a new id does not inherit the starter.+Every window showing the starter does this, and it is still one pane: the desk's `pane.add` is idempotent, and a+window the desk reaches first finds it already in a tab. The header says `started by <starter's current name>` where+it says `forked from` for a fork. Not yet: the phone, and harnesses started by agents outside Harness (no pane to open+beside), which stay in ⌘O as before.The task a harness is started with carries one header line, so the new harness knows it is from an agent and notthe person (the lamp team's tmux paste read as the owner's), and that its answer is read where it is:@@ -312,5 +342,5 @@ answer itself). Not yet run: Codex as the starting agent, a red team, a held-out## Not nowAn MCP server (a thin wrapper once the CLI holds), agents outside Harness (a Claude Code plugin, `npx`, the MCP-registries), the windows' tree of who started whom, `ps` across all machines (today: this one, and what you+registries), the windows' tree of who started whom beyond the pane beside its starter, `ps` across all machines (today: this one, and what youstarted elsewhere).