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
Fork a harness: a second agent with the first one's memory
0xdiego256ef0f44c760e
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 9bef7a600..e220ff3c5 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -1209,6 +1209,68 @@ describe('BackendSocket outbound queue', () => {})})+describe('agent_fork RPC', () => {+ afterEach(() => {+ wsMock.instances.length = 0+ vi.restoreAllMocks()+ })++ const FORK: RegisteredSession = {+ schemaVersion: 2, active: true, agentId: 'agent-2', sessionId: '', boundAt: null, engine: 'claude',+ forkedFrom: { agentId: 'agent-1', name: 'Agent one' },+ transcriptPath: null, projectDir: 'workspace', cwd: '/tmp/workspace', runtimes: [], primaryRuntimeKey: '',+ tmuxPane: '%2', source: null, title: null, model: null, cliVersion: null, processIdentity: null,+ registeredAt: 2, updatedAt: 2, lastHookAt: 2, lastTranscriptAt: 2,+ }++ function localSocket(): { socket: BackendSocket; frames: Array<Record<string, unknown>> } {+ const socket = new BackendSocket('token')+ const frames: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:fork', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })+ return { socket, frames }+ }++ it('validates the frame before touching the daemon', async () => {+ const { socket, frames } = localSocket()+ socket.handleLocalFrame('local:fork', { type: 'agent_fork', payload: { requestId: 'r1' } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'agent_fork_result', payload: { requestId: 'r1', error: 'MISSING_AGENT_ID' } }))+ socket.handleLocalFrame('local:fork', { type: 'agent_fork', payload: { requestId: 'r2', agentId: 'agent-1' } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'agent_fork_result', payload: { requestId: 'r2', error: 'UNSUPPORTED_ON_REMOTE' } }))+ socket.onForkAgent = async () => ({ ok: true, session: FORK, level: 'native' })+ socket.handleLocalFrame('local:fork', { type: 'agent_fork', payload: { requestId: 'r3', agentId: 'agent-1', prompt: 'x'.repeat(2001) } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'agent_fork_result', payload: { requestId: 'r3', error: 'PROMPT_TOO_LONG' } }))+ await socket.unregisterLocalClient('local:fork')+ await socket.stop()+ })++ it('hands name and prompt to the daemon and answers with the fork, its level, and who it came from', async () => {+ const { socket, frames } = localSocket()+ const seen: unknown[] = []+ socket.onForkAgent = async (input) => { seen.push(input); return { ok: true, session: FORK, level: 'native' } }+ socket.handleLocalFrame('local:fork', { type: 'agent_fork', payload: { requestId: 'r1', agentId: 'agent-1', name: ' Agent one - fork ', prompt: 'ship it' } })+ await vi.waitFor(() => {+ const result = frames.find((f) => f.type === 'agent_fork_result')+ expect(result).toMatchObject({+ payload: { requestId: 'r1', level: 'native', agent: expect.objectContaining({ id: 'agent-2', forkedFrom: { agentId: 'agent-1', name: 'Agent one' } }) },+ })+ })+ expect(seen).toEqual([{ agentId: 'agent-1', name: 'Agent one - fork', prompt: 'ship it' }])+ await socket.unregisterLocalClient('local:fork')+ await socket.stop()+ })++ it('relays the daemon\'s refusal with its reason', async () => {+ const { socket, frames } = localSocket()+ socket.onForkAgent = async () => ({ ok: false, error: 'AGENT_BUSY', detail: 'Wait for it to finish, then fork.' })+ socket.handleLocalFrame('local:fork', { type: 'agent_fork', payload: { requestId: 'r1', agentId: 'agent-1' } })+ await vi.waitFor(() => expect(frames).toContainEqual({+ type: 'agent_fork_result', payload: { requestId: 'r1', error: 'AGENT_BUSY', detail: 'Wait for it to finish, then fork.' },+ }))+ await socket.unregisterLocalClient('local:fork')+ await socket.stop()+ })+})+describe('agent_restart RPC', () => {afterEach(() => {wsMock.instances.length = 0diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 34d200c38..ca2d756ee 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -467,6 +467,14 @@ export class BackendSocket {{ ok: true; session: RegisteredSession; resumed: boolean }| { ok: false; error: string; detail?: string }>) | null = null+ /** Called on `agent_fork` — cli.ts opens a NEW agent that starts with `agentId`'s whole history+ * (lib/forkAgent.ts) and returns its process-agent, exactly as `agent_create` does. `level` says+ * what the new agent actually got: the engine's own fork, or a handoff message. */+ onForkAgent: ((input: { agentId: string; name: string | null; prompt: string | null }) =>+ Promise<+ { ok: true; session: RegisteredSession; level: 'native' | 'handoff' }+ | { ok: false; error: string; detail?: string }+ >) | null = null/** Called when the web/device sends chat input to an agent terminal. */onMessage: ((sessionId: string, content: string, deliveryId?: string) => void) | null = null/** Best-effort terminal-native title sync after a user renames an agent. */@@ -2084,6 +2092,26 @@ export class BackendSocket {return}+ // Fork an agent: a second one with the first one's history — see lib/forkAgent.ts. The reply+ // is agent_create's shape plus `level`, so a client opens the pane the same way.+ case 'agent_fork': {+ const target = payload.agentId as string | undefined+ if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }+ if (!this.onForkAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }+ const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim().slice(0, 120) : null+ const rawPrompt = payload.prompt+ if (rawPrompt !== undefined && rawPrompt !== null && typeof rawPrompt !== 'string') { reply(type, requestId, { error: 'INVALID_PROMPT' }); return }+ const prompt = typeof rawPrompt === 'string' && rawPrompt.trim() ? rawPrompt : null+ if (prompt && prompt.length > MAX_FIRST_PROMPT_CHARS) { reply(type, requestId, { error: 'PROMPT_TOO_LONG' }); return }+ const result = await this.onForkAgent({ agentId: target, name, prompt })+ if (!result.ok) {+ reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })+ return+ }+ reply(type, requestId, { agent: await this.toProject(result.session), level: result.level })+ return+ }+case 'agent_files': {// SourceTree list — rooted at the tmux session's working dir.const projectId = payload.agentId as string | undefineddiff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex bbbcf649f..6505bf2b0 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -355,6 +355,41 @@ describe('DaemonCableHost.listAgentsFlat across machines, and the tab the dial gexpect(opened).toHaveBeenCalledWith('other', 'r9')})+ it('forks a local agent through the daemon and opens the fork in the window', async () => {+ AGENTS.length = 0+ AGENTS.push({ agentId: 'a1', registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })+ const opened = vi.fn()+ const forkAgent = vi.fn(async () => ({ ok: true as const, agentId: 'a1-fork' }))+ const host = new DaemonCableHost(wiring({ opened, forkAgent }))+ await settled(host)++ expect(await host.forkAgent('a1')).toEqual({ ok: true, agentId: 'a1-fork' })+ expect(forkAgent).toHaveBeenCalledWith('a1')+ // The new agent lands in the window on its machine — before any list has named it. Through+ // `forked` when the wiring has it (beside its source), else the plain `opened`.+ expect(opened).toHaveBeenCalledWith('mine', 'a1-fork')+ const forked = vi.fn()+ const host2 = new DaemonCableHost(wiring({ opened, forked, forkAgent }))+ await settled(host2)+ await host2.forkAgent('a1')+ expect(forked).toHaveBeenCalledWith('mine', 'a1-fork', 'a1')+ expect(host.describe('a1-fork')).toMatchObject({ machine: 'MacbookPro.local' })+ })++ it('forks a remote agent on its own machine, and reports the far end\'s refusal', async () => {+ AGENTS.length = 0+ const opened = vi.fn()+ const fleet = crossFleet({ other: [{ id: 'r1', name: 'api' }] })+ fleet.forkAgent = vi.fn(async (_m: string, id: string) => { if (id === 'r1') return 'r1-fork'; throw new Error('r1 is in the middle of a turn') })+ const host = new DaemonCableHost(wiring({ opened }), fleet)+ await settled(host)++ expect(await host.forkAgent('r1')).toEqual({ ok: true, agentId: 'r1-fork' })+ expect(fleet.forkAgent).toHaveBeenCalledWith('other', 'r1')+ expect(opened).toHaveBeenCalledWith('other', 'r1-fork')+ expect(await host.forkAgent('ghost')).toMatchObject({ ok: false, error: 'AGENT_NOT_FOUND' })+ })+it('describes an agent it has listed, for a card about one the dial does not hold', async () => {AGENTS.length = 0AGENTS.push({ agentId: 'a1', registeredAt: 1, active: true, terminalAvailable: true, engine: 'codex' })diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 8f602a438..3a7b491be 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -52,6 +52,10 @@ export interface CableHostWiring {focused?: (machineId: string, agentId: string) => void/** A notification was tapped: the window gives that agent a tile of its own. */opened?: (machineId: string, agentId: string) => void+ /** A fork the dial asked for is open: the window puts it beside its source and focuses it. */+ forked?: (machineId: string, agentId: string, sourceAgentId: string) => void+ /** The dial asked for a fork of a LOCAL agent — see lib/forkAgent.ts. Resolves to the new agent's id. */+ forkAgent?: (agentId: string) => Promise<{ ok: true; agentId: string } | { ok: false; error: string; detail?: string }>/** The dial picked a swarm: the window switches to it. */swarmSelected?: (swarmId: string) => void/** A finger on the dial's glass, in pieces, while it is down. */@@ -526,6 +530,37 @@ export class DaemonCableHost implements CableHost {this.wiring.opened?.(machineId, agentId)}+ /**+ * Fork an agent from the dial: the same `agent_fork` the window sends, on the agent's own machine, and+ * then an `open` for the new agent so the window gives it a tile — the fork's whole point on the dial+ * is "this one, again, beside it", and the person's hand is on the dial, not the mouse.+ */+ async forkAgent(agentId: string): Promise<{ ok: true; agentId: string } | { ok: false; error: string; detail?: string }> {+ const machineId = this.machineOf(agentId)+ if (!machineId) return { ok: false, error: 'AGENT_NOT_FOUND', detail: 'The dial named an agent this daemon has never listed.' }+ let result: { ok: true; agentId: string } | { ok: false; error: string; detail?: string }+ if (this.isLocalAgent(agentId)) {+ if (!this.wiring.forkAgent) return { ok: false, error: 'UNSUPPORTED', detail: 'This daemon cannot fork agents.' }+ result = await this.wiring.forkAgent(agentId)+ } else {+ if (!this.fleet?.forkAgent) return { ok: false, error: 'UNSUPPORTED_ON_REMOTE' }+ try {+ result = { ok: true, agentId: await this.fleet.forkAgent(machineId, agentId) }+ } catch (err) {+ result = { ok: false, error: 'FORK_FAILED', detail: (err as Error).message }+ }+ }+ if (result.ok) {+ this.wiring.log(`cable: fork ${machineId}/${agentId} → ${result.agentId}`)+ this.seenOn.set(result.agentId, machineId)+ if (this.wiring.forked) this.wiring.forked(machineId, result.agentId, agentId)+ else this.wiring.opened?.(machineId, result.agentId)+ } else {+ this.wiring.log(`cable: fork ${machineId}/${agentId} refused (${result.error}${result.detail ? `: ${result.detail}` : ''})`)+ }+ return result+ }+/** Whether this daemon's last list held that agent — see CableHost.knows. */knows(agentId: string): boolean {return this.agentMachine.has(agentId)diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex b959e5f61..525f3954d 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -96,6 +96,7 @@ function makeHost(over: Partial<CableHost> = {}) {answer: vi.fn(),focus: vi.fn(),openAgent: vi.fn(),+ forkAgent: async (id) => ({ ok: true as const, agentId: `${id}-fork` }),updateAgent: vi.fn(),listModels: async () => ['runtime-v1:s1:claude:opus@high', 'runtime-v1:s1:claude:sonnet@low'],recentSummaries: async () => [],@@ -909,6 +910,26 @@ describe('cable session', () => {await session.stop()})+ it('forks on the dial\'s agent.fork and toasts only a refusal', async () => {+ const forkAgent = vi.fn(async (id: string) => id === 'a1'+ ? { ok: true as const, agentId: 'a1-fork' }+ : { ok: false as const, error: 'AGENT_BUSY', detail: 'Wait for it to finish, then fork.' })+ const { session, port } = await connect(makeHost({ forkAgent }))+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))+ port.sent.length = 0++ port.say({ t: 'agent.fork', agentId: 'a1' })+ await vi.waitFor(() => expect(forkAgent).toHaveBeenCalledWith('a1'))+ await new Promise((r) => setTimeout(r, 20))+ // The window is told through the host (`opened`); the dial hears nothing on success.+ expect(port.types().filter((t) => t === 'toast')).toEqual([])++ port.say({ t: 'agent.fork', agentId: 'a2' })+ await vi.waitFor(() => expect(port.sent.find((m) => m.t === 'toast')).toMatchObject({ text: 'Wait for it to finish, then fork.' }))+ await session.stop()+ })+it('names the agent on every summary and question, for one the dial does not hold', async () => {const { session, port } = await connect(makeHost({}))port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 79b73d657..a09db9a2c 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -235,6 +235,8 @@ export interface CableHost {* not a replacement for whatever the person was already watching.*/openAgent(agentId: string): void+ /** The dial asked for a fork of this agent — a second one with its history, opened in the window. */+ forkAgent(agentId: string): Promise<{ ok: true; agentId: string } | { ok: false; error: string; detail?: string }>/*** Does this daemon's own agent list hold that id?*@@ -805,6 +807,16 @@ export class CableSession {case 'agent.open':if (str('agentId')) this.host.openAgent(str('agentId')!)return+ case 'agent.fork': {+ // The dial's Fork action. The host opens the new agent in the window itself; the dial only needs+ // to hear a refusal, as a toast, so a press that did nothing is not a press that was lost.+ const id = str('agentId')+ if (!id) return+ void this.host.forkAgent(id).then((result) => {+ if (!result.ok) return this.toast(result.detail ?? result.error)+ }).catch((err) => this.toast((err as Error).message))+ return+ }case 'scroll': {// Forwarded verbatim, including the reports carrying no travel: the two ends of a stroke are the// whole point of the message. A `down` with nothing in it stops a fling still running, and an `up`diff --git a/cli/src/cable/machineFleet.ts b/cli/src/cable/machineFleet.tsindex 945e70809..75b51385b 100644--- a/cli/src/cable/machineFleet.ts+++ b/cli/src/cable/machineFleet.ts@@ -71,6 +71,9 @@ export interface MachineFleet {stopTurn(machineId: string, agentId: string): voidanswer(machineId: string, agentId: string, requestId: string, answers: Record<string, string>): voidupdateAgent(machineId: string, agentId: string, model?: string, effort?: string): void+ /** Fork an agent on that machine (`agent_fork`); resolves to the new agent's id, rejects with the+ * far end's refusal. Optional: a fleet built before forks existed simply cannot. */+ forkAgent?(machineId: string, agentId: string): Promise<string>listModels(machineId: string, agentId: string): Promise<string[]>recentSummaries(machineId: string, agentId: string): Promise<RecentTurn[]>/** The person's own last questions to that agent, newest first — the router's input. */diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 0eb54074a..b6bdb3f7c 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -79,6 +79,7 @@ import { claudeContinuation, findLiveSession } from './lib/sessionRepair.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from './lib/hostTheme.js'import { createAndRegisterPane } from './lib/createAgentPane.js'+import { forkName, planFork } from './lib/forkAgent.js'import { restoreAgents } from './lib/restoreAgents.js'import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'import { prepareCodexResume } from './engines/codex/portableHistory.js'@@ -2421,7 +2422,20 @@ async function runForeground(session: AuthSession): Promise<void> {}+ /**+ * Forks whose engine session has not reported in yet, agentId → the SOURCE's sessionId. A fork's tile+ * should open with the source's last recap on it, the way its pane opens with the source's transcript+ * — but the mirror keys by session, and the fork's session id is the engine's to name, minutes later+ * over a hook. Settled the moment it binds, below.+ */+ const pendingForkInherit = new Map<string, string>()+const handleRegistered = async (entry: RegisteredSession, meta: RegisteredMeta): Promise<void> => {+ const forkSource = pendingForkInherit.get(entry.agentId)+ if (forkSource && entry.sessionId) {+ pendingForkInherit.delete(entry.agentId)+ mirror.inheritSummary(forkSource, entry.sessionId)+ }if (meta.rebound) {registry.inheritName(meta.rebound, entry.sessionId)mirror.inheritSummary(meta.rebound, entry.sessionId)@@ -3902,6 +3916,61 @@ async function runForeground(session: AuthSession): Promise<void> {* pass can miss it — retry `triggerHint` a few times with backoff before giving up.*/+ /**+ * Watch a pane this daemon just opened until its engine process shows up (ready), dies (failed), or+ * ten minutes pass. Shared by create and fork: the two open panes the same way and wait the same way.+ */+ const watchNewPane = async (engine: AgentEngine, pending: RegisteredSession, spawned: { runtime: TmuxRuntimeRef }, command: string[], installIfMissing: ReturnType<typeof engineInstallRecipe> | undefined): Promise<void> => {+ const budgetMs = 10 * 60_000+ const startedAt = Date.now()+ let delayMs = 50+ try {+ while (Date.now() - startedAt < budgetMs) {+ if (!registry.byAgent(pending.agentId)) return+ const processIdentity = await resolvePaneEngineProcess(spawned.runtime.paneId, engine)+ if (processIdentity) {+ registry.updateProcessIdentity(pending.agentId, processIdentity)+ const ready = registry.setLaunch(pending.agentId, { state: 'ready' })+ await clearPaneRemainOnExit(spawned.runtime.paneId)+ if (ready) announceSession(ready)+ void agentReconciler.triggerHint(spawned.runtime, engine).catch((error) => {+ console.warn(`[agent] background bind failed · ${engine} · ${error instanceof Error ? error.message : error}`)+ })+ console.log(`[agent] create ready · ${engine} · agent ${pending.agentId} · ${Date.now() - startedAt}ms`)+ return+ }+ const paneState = await tmuxPaneState(spawned.runtime.paneId)+ if (!paneState) {+ registry.setTerminalAvailable(pending.agentId, false)+ announceSession(pending)+ return+ }+ if (paneState.dead) {+ const installed = await commandAvailableInInteractiveShell(command[0], undefined, installIfMissing)+ const error = installed ? 'ENGINE_DID_NOT_START' : 'ENGINE_NOT_INSTALLED'+ const detail = installed+ ? `${engine} exited before its engine process became ready. See the terminal output for details.`+ : `${engine} is not installed, or its automatic install failed. See the terminal output for details.`+ const failed = registry.setLaunch(pending.agentId, { state: 'failed', error, detail })+ if (failed) announceSession(failed)+ console.warn(`[agent] create failed · ${engine} · ${detail}`)+ return+ }+ await new Promise<void>((resolve) => {+ const timer = setTimeout(resolve, delayMs)+ timer.unref?.()+ })+ delayMs = Math.min(delayMs * 2, 750)+ }+ const detail = `${engine} did not expose an engine process within 10 minutes. The terminal remains available.`+ const failed = registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT', detail })+ if (failed) announceSession(failed)+ console.warn(`[agent] create timed out · ${engine} · agent ${pending.agentId}`)+ } catch (error) {+ console.warn(`[agent] create watch failed · ${engine} · ${error instanceof Error ? error.message : error}`)+ }+ }+backend.onCreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent }) => {if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }try {@@ -4050,61 +4119,105 @@ async function runForeground(session: AuthSession): Promise<void> {announceSession(pending)if (pending.dsh) attachDsh(pending)- const watchCreatedPane = async (): Promise<void> => {- const budgetMs = 10 * 60_000- const startedAt = Date.now()- let delayMs = 50- try {- while (Date.now() - startedAt < budgetMs) {- if (!registry.byAgent(pending.agentId)) return- const processIdentity = await resolvePaneEngineProcess(spawned.runtime.paneId, engine)- if (processIdentity) {- registry.updateProcessIdentity(pending.agentId, processIdentity)- const ready = registry.setLaunch(pending.agentId, { state: 'ready' })- await clearPaneRemainOnExit(spawned.runtime.paneId)- if (ready) announceSession(ready)- void agentReconciler.triggerHint(spawned.runtime, engine).catch((error) => {- console.warn(`[agent] background bind failed · ${engine} · ${error instanceof Error ? error.message : error}`)- })- console.log(`[agent] create ready · ${engine} · agent ${pending.agentId} · ${Date.now() - startedAt}ms`)- return- }- const paneState = await tmuxPaneState(spawned.runtime.paneId)- if (!paneState) {- registry.setTerminalAvailable(pending.agentId, false)- announceSession(pending)- return- }- if (paneState.dead) {- const installed = await commandAvailableInInteractiveShell(command[0], undefined, installIfMissing)- const error = installed ? 'ENGINE_DID_NOT_START' : 'ENGINE_NOT_INSTALLED'- const detail = installed- ? `${engine} exited before its engine process became ready. See the terminal output for details.`- : `${engine} is not installed, or its automatic install failed. See the terminal output for details.`- const failed = registry.setLaunch(pending.agentId, { state: 'failed', error, detail })- if (failed) announceSession(failed)- console.warn(`[agent] create failed · ${engine} · ${detail}`)- return- }- await new Promise<void>((resolve) => {- const timer = setTimeout(resolve, delayMs)- timer.unref?.()- })- delayMs = Math.min(delayMs * 2, 750)- }- const detail = `${engine} did not expose an engine process within 10 minutes. The terminal remains available.`- const failed = registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT', detail })- if (failed) announceSession(failed)- console.warn(`[agent] create timed out · ${engine} · agent ${pending.agentId}`)- } catch (error) {- console.warn(`[agent] create watch failed · ${engine} · ${error instanceof Error ? error.message : error}`)- }- }- void watchCreatedPane()+ void watchNewPane(engine, pending, spawned, command, installIfMissing)console.log(`[agent] create pane open · ${engine} · agent ${pending.agentId}`)return { ok: true, session: pending }}+ /**+ * Fork an agent (`agent_fork`): open a NEW pane whose engine starts with everything the source's+ * session has — `claude --resume <id> --fork-session`, `codex fork <id>` — or, for an engine that+ * cannot fork but takes a first prompt, a handoff message composed from what this daemon remembers+ * of the source (lib/forkAgent.ts). Same folder, same harness, same permission mode, same named+ * agent; a grid agent is refused rather than half-copied. The source is not touched — it is not even+ * paused — which is why it has to be IDLE: a fork taken mid-turn is a transcript cut in half.+ */+ backend.onForkAgent = async ({ agentId, name, prompt }) => {+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }+ const source = registry.byAgent(agentId)+ if (!source) return { ok: false, error: 'AGENT_NOT_FOUND' }+ const sourceName = projectDisplayName(source)+ if (!source.cwd) return { ok: false, error: 'CWD_NOT_FOUND', detail: `${sourceName} has no working folder on record.` }+ try {+ if (!statSync(source.cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }+ } catch {+ return { ok: false, error: 'CWD_NOT_FOUND' }+ }+ if (source.gridLaunch || source.grid) {+ return { ok: false, error: 'FORK_ON_GRID_UNSUPPORTED', detail: `${sourceName} runs on a grid; forking a grid agent is not supported.` }+ }+ if (source.sessionId && mirror.isBusy(source.sessionId)) {+ return { ok: false, error: 'AGENT_BUSY', detail: `${sourceName} is in the middle of a turn. Wait for it to finish, then fork.` }+ }+ const engine = source.engine+ const memory = {+ asks: source.sessionId ? mirror.recentAsks(source.sessionId) : [],+ recaps: source.sessionId ? mirror.recent(source.sessionId, 5).map((t) => t.recap || t.text) : [],+ lastAnswer: source.sessionId ? mirror.lastFullText(source.sessionId) : undefined,+ }+ const plan = planFork({ engine, sessionId: source.sessionId, name: sourceName, cwd: source.cwd }, memory, prompt)+ if (!plan.ok) return { ok: false, error: plan.error, detail: plan.detail }++ // The harness the source was created as: its env and argv, not a second materialisation — the+ // folder already holds the template, AGENTS.md and skill links the source got.+ let dshEnv: Record<string, string> | undefined+ let dshArgs: string[] = []+ let dshLabel: string | undefined+ if (source.dsh) {+ const installed = installedDsh(source.dsh)+ if (!installed) return { ok: false, error: 'INVALID_DSH', detail: `${source.dsh} is no longer installed on this machine` }+ const launch = dshLaunch(installed, source.cwd)+ dshEnv = launch.env+ dshArgs = launch.args+ dshLabel = installed.manifest.name+ }+ const label = buildHarnessSessionLabel(engine)+ const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)+ const extraArgs = [...dshArgs, ...(source.agent ? namedAgentArgs(engine, source.agent) : [])]+ const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPrompt+ const launchOptions = {+ bypassPermission: source.bypassPermission ?? false,+ ...(source.permissionMode ? { permissionMode: source.permissionMode } : {}),+ extraArgs: extraArgs.length ? extraArgs : undefined,+ installIfMissing,+ cwd: source.cwd,+ harnessNode: source.dsh ? true : undefined,+ ...(plan.level === 'native' ? { forkSessionId: plan.forkSessionId } : {}),+ ...(firstPrompt ? { firstPrompt } : {}),+ }+ const command = buildEngineCommandArgv(engine, launchOptions)+ const argv = buildEngineLaunchArgv(engine, launchOptions)+ const result = await createAndRegisterPane({+ tmuxBackend,+ registry,+ engine,+ cwd: source.cwd,+ sessionLabel: label,+ argv,+ env: mergedLaunchEnv(source.codexHome ? { CODEX_HOME: source.codexHome } : undefined, dshEnv),+ grid: null,+ gridLaunchRecord: null,+ codexHome: source.codexHome ?? null,+ dsh: source.dsh ?? null,+ agent: source.agent ?? null,+ bypassPermission: source.bypassPermission ?? false,+ permissionMode: source.permissionMode ?? null,+ defaultName: name ?? forkName(sourceName),+ label: dshLabel,+ forkedFrom: { agentId: source.agentId, name: sourceName },+ })+ if (!result.ok) return { ok: false, error: result.error, detail: result.detail }+ const { spawned, pending } = result+ // The new tile starts with the source's last recap on it, the way a native fork's pane starts with+ // the source's transcript: memory in both places, not one. Settled when the engine names its session.+ if (source.sessionId) pendingForkInherit.set(pending.agentId, source.sessionId)+ announceSession(pending)+ if (pending.dsh) attachDsh(pending)+ void watchNewPane(engine, pending, spawned, command, installIfMissing)+ console.log(`[agent] fork pane open · ${engine} · ${plan.level} · ${source.agentId} → ${pending.agentId}`)+ return { ok: true, session: pending, level: plan.level }+ }+/*** The dependencies a pane-process swap needs, for both callers that do one.*@@ -4824,6 +4937,13 @@ async function runForeground(session: AuthSession): Promise<void> {// at another computer entirely.// A notification tap, which asks for a tile of its OWN — see CableHost.openAgent.opened: (machineId, agentId) => backend.sendLocal({ type: 'dial_open', payload: { machineId, agentId } }),+ forked: (machineId, agentId, sourceAgentId) => backend.sendLocal({ type: 'dial_forked', payload: { machineId, agentId, sourceAgentId } }),+ // The dial's Fork: the same path the window's `agent_fork` takes, then `forked` above lands on it.+ forkAgent: async (agentId) => {+ if (!backend.onForkAgent) return { ok: false, error: 'UNSUPPORTED' }+ const result = await backend.onForkAgent({ agentId, name: null, prompt: null })+ return result.ok ? { ok: true, agentId: result.session.agentId } : { ok: false, error: result.error, detail: result.detail }+ },// No `edge`. It used to ride along for an agent the window had no tile for, naming which end of the// desk to replace; the carousel now only walks tiles that exist, so every focus is about one of them.focused: (machineId, agentId) =>diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.tsindex ba1c01420..a933264e3 100644--- a/cli/src/device/deviceFleet.ts+++ b/cli/src/device/deviceFleet.ts@@ -232,6 +232,14 @@ export class DeviceFleet implements MachineFleet {.catch((err) => this.opts.log(`device: agent_update failed (${(err as Error).message})`))}+ async forkAgent(machineId: string, agentId: string): Promise<string> {+ const res = await this.rpc(machineId, 'agent_fork', { agentId })+ const agent = res.agent as { id?: unknown } | undefined+ if (typeof res.error === 'string') throw new Error(typeof res.detail === 'string' ? res.detail : res.error)+ if (typeof agent?.id !== 'string' || !agent.id) throw new Error('the machine answered without an agent')+ return agent.id+ }+async listModels(machineId: string, agentId: string): Promise<string[]> {// `compact` is what keeps the catalog inside the dial's picker; the backend trims to ≤24 entries.diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex b1814a399..b64b87165 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -23,6 +23,7 @@ import { agentProject, type AgentProject } from './agentProject.js'import type { GridAssignment } from './gridAssignment.js'import type { GridWebSearchStatus } from './gridLaunch.js'import { projectDisplayName, sessionDisplayTitle, type RegisteredSession } from './registry.js'+import { engineCanFork } from './forkAgent.js'import type { DshVerdict } from '../dsh/verdict.js'/**@@ -72,6 +73,11 @@ export type AgentFrame = {viewerName: string | null/** The DSH's last verdict for this workspace, reduced for the pane header; null when none yet. */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+ /** 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}/** What the daemon knows about an agent's DSH — looked up by the caller, never here. */@@ -144,5 +150,7 @@ export async function agentFrame(viewerUrl: dsh?.viewerUrl ?? null,viewerName: dsh?.viewerName ?? null,verdict: dsh?.verdict ?? null,+ forkedFrom: s.forkedFrom ? { agentId: s.forkedFrom.agentId, name: s.forkedFrom.name } : null,+ forkable: engineCanFork(s.engine),}}diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.tsindex f16b0f685..2880ed948 100644--- a/cli/src/lib/commander.ts+++ b/cli/src/lib/commander.ts@@ -703,6 +703,12 @@ export class CommanderMirror {* window (Summarizing…) — the device clears a busy tile only via a live terminal, and has a busy-timeout* watchdog that fires if these stop arriving. Returns true while the session is busy (turnOpen ||* summarizing) so the caller knows when to self-cancel the timer; false (emitting nothing) when idle. */+ /** A turn is open on this session right now. Summarising after one does not count: the transcript is+ * complete, which is what a fork needs. */+ isBusy(sessionId: string): boolean {+ return this.states.get(sessionId)?.turnOpen === true+ }+heartbeat(sessionId: string): boolean {const st = this.states.get(sessionId)if (!st) return falsediff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.tsindex 5370cde5c..36e8b6f51 100644--- a/cli/src/lib/createAgentPane.ts+++ b/cli/src/lib/createAgentPane.ts@@ -37,6 +37,7 @@ export interface CreateAgentPaneDeps {permissionMode?: string | nulldefaultName?: string | nulllabel?: string | null+ forkedFrom?: { agentId: string; name: string } | null}) => RegisteredSession | null }engine: AgentEnginecwd?: string | null@@ -62,6 +63,8 @@ export interface CreateAgentPaneDeps {/** The engine's named agent the pane opens as (`agent_create`'s `agent`); kept on the row so a* relaunch opens as it again. Already in `argv` — this is the record, not the launch. */agent?: string | null+ /** The agent this pane is a fork of (`agent_fork`), recorded on the row; null otherwise. */+ forkedFrom?: { agentId: string; name: string } | nullmaxAttempts?: number}@@ -101,6 +104,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<permissionMode: deps.permissionMode,defaultName: deps.defaultName,label: deps.label,+ forkedFrom: deps.forkedFrom,})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/e2ee/core.ts b/cli/src/lib/e2ee/core.tsindex 9dd3e5850..640f644c7 100644--- a/cli/src/lib/e2ee/core.ts+++ b/cli/src/lib/e2ee/core.ts@@ -350,6 +350,8 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([// Device RPC replies that carry adapter content (recap headline/body, new agent name). Must be// ciphertext so the backend relay can't read them — device↔adapter E2EE parity with web.'agent_recent_result', 'agent_create_result', 'agent_create_status_result', 'agent_restart_result',+ // A fork's reply names the new agent, exactly like agent_create's.+ 'agent_fork_result',// A remote-machine directory listing (New Agent folder browser) — leaks filesystem layout if plaintext.'fs_list_dir_result', 'project_preview_result',// Same reasoning as fs_list_dir_result: reveals Codex profile folder names/paths on this machine.@@ -372,6 +374,8 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>(['question_response','agents_list', 'sessions_list', 'session_get', 'models_list','agent_create', 'agent_create_status', 'agent_delete', 'agent_restart', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',+ // Carries the fork's name and first task — what the person typed — like agent_create's prompt.+ 'agent_fork','fs_list_dir', 'project_preview', 'codex_profiles_list', 'codex_profile_link',// Asks this machine to read its own agent accounts' usage (lib/accountUsage.ts). ⚠️ Missing here it// would not fail loudly — the same trap `question_response` once fell into: the payload would staydiff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex fc974173f..73e558025 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -191,6 +191,9 @@ export interface LaunchCommandOptions {permissionMode?: string/** Resume this engine session id on launch, when a launch-resume flag is known for the engine. */resumeSessionId?: string+ /** FORK this engine session id on launch — a new session that starts with its history, the source+ * untouched ([LAUNCH_FORK_FLAG]). Takes precedence over `resumeSessionId`. */+ forkSessionId?: string/*** The message the session opens with, already submitted — see [FIRST_PROMPT_ARGS]. Appended LAST,* after every flag, because two of the three engines take it positionally and a positional is only@@ -290,15 +293,38 @@ export const LAUNCH_RESUME_FLAG: Readonly<Partial<Record<AgentEngine, string[]>>copilot: ['--resume'],}+/**+ * "Open a NEW session that starts with everything session <id> has" — a fork, per engine. Confirmed+ * against each CLI's own `--help` (2026-09-18): `claude --resume <id> --fork-session` ("When resuming,+ * create a new session ID") and `codex fork <id>` ("Fork a previous interactive session"). The source+ * session is left exactly as it was; the two then diverge.+ *+ * Same shape rule as [LAUNCH_RESUME_FLAG]: a leading token that does not start with `-` is a+ * subcommand and goes first. `after` is appended once the id is in place. An engine absent here has no+ * native fork; `forkAgent.ts` falls back to a handoff (a composed first prompt) where the engine takes+ * one, and refuses otherwise — never a plain `--resume`, which would put two processes on ONE session.+ */+export const LAUNCH_FORK_FLAG: Readonly<Partial<Record<AgentEngine, { lead: string[]; after?: string[] }>>> = {+ claude: { lead: ['--resume'], after: ['--fork-session'] },+ codex: { lead: ['fork'] },+}++export function supportsNativeFork(engine: AgentEngine): boolean {+ return LAUNCH_FORK_FLAG[engine] !== undefined+}+/** The executable argv, before the interactive-shell wrapper is applied. */export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandOptions = {}): string[] {const argv = [engineBin(engine)]- const resumeFlag = opts.resumeSessionId ? LAUNCH_RESUME_FLAG[engine] : undefined+ // A fork is a resume that leaves the source alone; the two are exclusive, and the fork wins.+ const fork = opts.forkSessionId ? LAUNCH_FORK_FLAG[engine] : undefined+ const resumeFlag = fork ? fork.lead : opts.resumeSessionId ? LAUNCH_RESUME_FLAG[engine] : undefined+ const sessionArg = fork ? opts.forkSessionId : opts.resumeSessionIdconst resumeIsSubcommand = !!resumeFlag?.length && !resumeFlag[0].startsWith('-')// Subcommand-style resume (`codex resume <id>`, `amp threads continue <id>`, `muse resume <id>`) is// parsed positionally and must be the first argv after the binary, ahead of any other flag.- if (resumeIsSubcommand && resumeFlag && opts.resumeSessionId) {- argv.push(...resumeFlag, opts.resumeSessionId)+ if (resumeIsSubcommand && resumeFlag && sessionArg) {+ argv.push(...resumeFlag, sessionArg, ...(fork?.after ?? []))}const modeFlags = opts.permissionMode ? permissionModeFlags(engine, opts.permissionMode) : nullif (modeFlags) {@@ -307,8 +333,8 @@ export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandOconst flags = BYPASS_PERMISSION_FLAGS[engine]if (flags) argv.push(...flags)}- if (!resumeIsSubcommand && resumeFlag && opts.resumeSessionId) {- argv.push(...resumeFlag, opts.resumeSessionId)+ if (!resumeIsSubcommand && resumeFlag && sessionArg) {+ argv.push(...resumeFlag, sessionArg, ...(fork?.after ?? []))}if (opts.extraArgs?.length) argv.push(...opts.extraArgs)if (opts.firstPrompt) argv.push(...firstPromptArgs(engine, opts.firstPrompt))diff --git a/cli/src/lib/forkAgent.spec.ts b/cli/src/lib/forkAgent.spec.tsnew file mode 100644index 000000000..57866dcee--- /dev/null+++ b/cli/src/lib/forkAgent.spec.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest'++import { buildEngineCommandArgv, MAX_FIRST_PROMPT_CHARS } from './engineLaunch.js'+import { forkName, handoffPrompt, planFork } from './forkAgent.js'++const memory = { asks: ['make the tests green', 'add a login form'], recaps: ['3 tests fixed', 'form added with validation'], lastAnswer: 'All green now.' }++describe('planFork', () => {+ it('forks Claude and Codex natively, with the argv each CLI documents', () => {+ const claude = planFork({ engine: 'claude', sessionId: 's-1', name: 'Kinh Te', cwd: '/w' }, memory, null)+ expect(claude).toEqual({ ok: true, level: 'native', forkSessionId: 's-1' })+ // `claude --resume <id> --fork-session`: the flag rides after the id, ahead of the first prompt.+ const argv = buildEngineCommandArgv('claude', { forkSessionId: 's-1', firstPrompt: 'go' })+ expect(argv.slice(-4)).toEqual(['--resume', 's-1', '--fork-session', 'go'])+ // `codex fork <id> [PROMPT]`: a subcommand, first after the binary.+ expect(buildEngineCommandArgv('codex', { forkSessionId: 's-2', firstPrompt: 'go' }).slice(0, 3)).toEqual(['codex', 'fork', 's-2'])+ expect(buildEngineCommandArgv('codex', { forkSessionId: 's-2', firstPrompt: 'go' }).at(-1)).toBe('go')+ })++ it('refuses a native fork of a session the engine has not named yet', () => {+ const plan = planFork({ engine: 'claude', sessionId: '', name: 'Fresh', cwd: null }, memory, null)+ expect(plan).toMatchObject({ ok: false, error: 'FORK_NO_SESSION' })+ })++ it('hands off through a first prompt when the engine takes one but cannot fork', () => {+ const plan = planFork({ engine: 'opencode', sessionId: 'x', name: 'Ops', cwd: '/srv' }, memory, 'ship it')+ expect(plan.ok && plan.level).toBe('handoff')+ if (!plan.ok || plan.level !== 'handoff') return+ // Oldest first, the person's words and the result side by side, the task last.+ expect(plan.firstPrompt.indexOf('add a login form')).toBeLessThan(plan.firstPrompt.indexOf('make the tests green'))+ expect(plan.firstPrompt).toContain('Result: 3 tests fixed')+ expect(plan.firstPrompt).toContain('Its last full answer:\nAll green now.')+ expect(plan.firstPrompt.endsWith('Your task now: ship it')).toBe(true)+ expect(plan.firstPrompt).toContain('fork of the agent "Ops" in /srv')+ })++ it('refuses an engine with neither a fork nor a first prompt, and says why', () => {+ const plan = planFork({ engine: 'cursor', sessionId: 'x', name: 'C', cwd: null }, memory, null)+ expect(plan).toMatchObject({ ok: false, error: 'FORK_UNSUPPORTED' })+ expect(!plan.ok && plan.detail).toContain('cursor')+ })++ it('a fork never becomes a plain resume', () => {+ // Two processes on one session is the failure this whole module exists to avoid.+ expect(buildEngineCommandArgv('claude', { forkSessionId: 's-1', resumeSessionId: 's-1' })).toContain('--fork-session')+ // An engine without a fork gets no session argument at all from a fork request.+ expect(buildEngineCommandArgv('cursor', { forkSessionId: 's-1' })).toEqual(buildEngineCommandArgv('cursor', {}))+ })+})++describe('handoffPrompt', () => {+ it('drops the oldest turns first to fit the wire', () => {+ const big = { asks: Array.from({ length: 40 }, (_, i) => `ask ${i} ${'x'.repeat(80)}`), recaps: Array.from({ length: 40 }, (_, i) => `recap ${i}`), lastAnswer: 'y'.repeat(300) }+ const text = handoffPrompt({ engine: 'opencode', sessionId: 'x', name: 'N', cwd: null }, big, null)+ expect(text.length).toBeLessThanOrEqual(MAX_FIRST_PROMPT_CHARS)+ expect(text).toContain('ask 0 ') // the newest (index 0) survives+ expect(text).not.toContain('ask 39 ') // the oldest goes first+ expect(text).toContain('Continue from there.')+ })++ it('asks for a one-line state check when there is no task', () => {+ const text = handoffPrompt({ engine: 'opencode', sessionId: 'x', name: 'N', cwd: null }, { asks: [], recaps: [] }, ' ')+ expect(text).toContain('say in one line what you understand the current state to be')+ })+})++describe('forkName', () => {+ it('is the source name with " - fork"', () => {+ expect(forkName('Kinh Te')).toBe('Kinh Te - fork')+ expect(forkName(' ')).toBe('Agent - fork')+ })+})diff --git a/cli/src/lib/forkAgent.ts b/cli/src/lib/forkAgent.tsnew file mode 100644index 000000000..40309c00b--- /dev/null+++ b/cli/src/lib/forkAgent.ts@@ -0,0 +1,117 @@+/**+ * Fork a harness: a SECOND agent that starts with everything the first one knows, then goes its own way.+ *+ * Not resume (the same session, continued) and not clone (a new agent, empty). Claude Code's+ * `--resume <id> --fork-session` and Codex's `codex fork <id>`, as a Harness verb, with a fallback for+ * the engines that have no such thing.+ *+ * Three levels, decided here per engine and announced to the person in the pane:+ * - native — the engine opens a new session from the old one (`LAUNCH_FORK_FLAG`). Full context.+ * - handoff — the engine takes a first prompt but cannot fork: the new agent opens with a message+ * composed from what the daemon remembers of the source (its recent asks and recaps,+ * its last full answer) and is told to carry on from there. Memory, not context.+ * - refused — no fork, no first prompt: there is no honest way to give the new agent the old one's+ * history, and a plain `--resume` would put two processes on ONE session.+ *+ * The launch itself goes down `agent_create`'s path (cli.ts, `onForkAgent`); this module decides what+ * that launch is and writes the handoff. Pure, so both are testable without tmux.+ */+import type { AgentEngine } from '../engines/types.js'+import { MAX_FIRST_PROMPT_CHARS, supportsFirstPrompt, supportsNativeFork } from './engineLaunch.js'++export type ForkLevel = 'native' | 'handoff'++/** Whether a fork of an agent on this engine can be anything at all — native or a handoff. */+export function engineCanFork(engine: AgentEngine): boolean {+ return supportsNativeFork(engine) || supportsFirstPrompt(engine)+}++export type ForkPlan =+ | { ok: true; level: 'native'; forkSessionId: string }+ | { ok: true; level: 'handoff'; firstPrompt: string }+ | { ok: false; error: 'FORK_UNSUPPORTED' | 'FORK_NO_SESSION'; detail: string }++/** What the daemon remembers of the source, in the mirror's own terms (commander.ts). */+export interface ForkMemory {+ /** The person's own words for the recent turns, newest first. */+ asks: string[]+ /** One-line recaps of the recent turns, newest first. */+ recaps: string[]+ /** The newest turn's complete answer, if kept. */+ lastAnswer?: string+}++export interface ForkSource {+ engine: AgentEngine+ /** The engine session bound to the source, '' when the engine has not reported one yet. */+ sessionId: string+ name: string+ cwd: string | null+}++/**+ * Decide how `source` can be forked.+ *+ * `task` is what the person typed into the fork dialog's First task — for a native fork it is passed+ * through as the new session's first prompt; for a handoff it is folded into the composed message so+ * the new agent gets its history AND its job in one turn rather than two.+ */+export function planFork(source: ForkSource, memory: ForkMemory, task: string | null): ForkPlan {+ if (supportsNativeFork(source.engine)) {+ if (!source.sessionId) {+ return {+ ok: false, error: 'FORK_NO_SESSION',+ detail: `${source.name} has not started a session yet — there is nothing to fork until it has answered once.`,+ }+ }+ return { ok: true, level: 'native', forkSessionId: source.sessionId }+ }+ if (!supportsFirstPrompt(source.engine)) {+ return {+ ok: false, error: 'FORK_UNSUPPORTED',+ detail: `${source.engine} can neither fork a session nor open with a first message, so a fork of ${source.name} would start empty.`,+ }+ }+ return { ok: true, level: 'handoff', firstPrompt: handoffPrompt(source, memory, task) }+}++/**+ * The message a handoff fork opens with.+ *+ * Written as a briefing from the previous agent, not as a system prompt: the engine reads it as the+ * person's first turn, and a first turn that reads like a document gets answered like one. Newest+ * facts last, so the "continue from here" lands beside the freshest context. Clipped to what the wire+ * accepts (`MAX_FIRST_PROMPT_CHARS`), oldest history first to go.+ */+export function handoffPrompt(source: ForkSource, memory: ForkMemory, task: string | null): string {+ const where = source.cwd ? ` in ${source.cwd}` : ''+ const head = `You are a fork of the agent "${source.name}"${where}. It kept working; you are its copy, picking up from what it knew. Here is its recent history, oldest first.`+ const turns: string[] = []+ const n = Math.max(memory.asks.length, memory.recaps.length)+ for (let i = n - 1; i >= 0; i--) {+ const ask = (memory.asks[i] ?? '').trim()+ const recap = (memory.recaps[i] ?? '').trim()+ if (!ask && !recap) continue+ turns.push([ask ? `Asked: ${ask}` : '', recap ? `Result: ${recap}` : ''].filter(Boolean).join('\n'))+ }+ const answer = (memory.lastAnswer ?? '').trim()+ const tail = task?.trim()+ ? `Continue from there. Your task now: ${task.trim()}`+ : 'Continue from there. Before acting, say in one line what you understand the current state to be.'++ // Assemble from the fixed parts outward, dropping the oldest turns first until it fits.+ const fixed = [head, answer ? `Its last full answer:\n${answer}` : '', tail]+ let kept = turns+ for (;;) {+ const body = [fixed[0], ...(kept.length ? [kept.join('\n\n')] : []), fixed[1], fixed[2]].filter(Boolean).join('\n\n')+ if (body.length <= MAX_FIRST_PROMPT_CHARS) return body+ if (kept.length) { kept = kept.slice(1); continue }+ if (fixed[1]) { fixed[1] = ''; continue }+ return body.slice(0, MAX_FIRST_PROMPT_CHARS)+ }+}++/** The default name for a fork of `name` — the owner's spelling (2026-09-18). */+export function forkName(name: string): string {+ return `${name.trim() || 'Agent'} - fork`+}diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex bd4d0daa5..1d034a261 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -169,6 +169,13 @@ export interface RegisteredSession {* existed and on agents Harness did not launch; those relaunch from `bypassPermission`.*/permissionMode?: string+ /**+ * The agent this one was FORKED from (`agent_fork`): a new session opened with the source's whole+ * history, the source left as it was. Recorded once at creation so the pane can say "forked from X"+ * and link back; `name` is the source's name at that moment, kept because the source may be renamed+ * or gone by the time anyone reads it. Absent on every other agent.+ */+ forkedFrom?: { agentId: string; name: string } | null/** Legacy launcher-owned snapshots may still contain this field. New records never write it. */launcherId?: stringtranscriptPath: string | null@@ -464,6 +471,7 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {projectDir: row.projectDir,defaultName: normalizedDefaultName(row.defaultName),agent: normalizedAgentName((row as { agent?: unknown }).agent),+ ...(normalizedForkedFrom((row as { forkedFrom?: unknown }).forkedFrom)),cwd: typeof row.cwd === 'string' ? row.cwd : null,runtimes,primaryRuntimeKey: normalizedPrimary,@@ -480,6 +488,14 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {}}+/** `forkedFrom` as written by this daemon, or nothing: a row from before the field, or a hand-edited one. */+function normalizedForkedFrom(value: unknown): { forkedFrom: { agentId: string; name: string } } | Record<string, never> {+ if (!value || typeof value !== 'object') return {}+ const v = value as { agentId?: unknown; name?: unknown }+ if (typeof v.agentId !== 'string' || !v.agentId) return {}+ return { forkedFrom: { agentId: v.agentId, name: typeof v.name === 'string' ? v.name.slice(0, 120) : '' } }+}+function normalizedLaunch(value: unknown): AgentLaunch | undefined {if (!value || typeof value !== 'object') return undefinedconst launch = value as { state?: unknown; error?: unknown; detail?: unknown }@@ -1086,6 +1102,8 @@ class Registry {defaultName?: string | null/** Who the agent is, for the name Harness gives it: a DSH's own name ("Blender"); the engine's by default. */label?: string | null+ /** The agent this one is a fork of — see RegisteredSession.forkedFrom. */+ forkedFrom?: { agentId: string; name: string } | null}): RegisteredSession | null {if (this.writeBlocked) return nullconst runtimes = normalizedRuntimes(input.runtimes)@@ -1111,6 +1129,7 @@ class Registry {agent: normalizedAgentName(input.agent),...(input.bypassPermission ? { bypassPermission: true } : {}),...(permissionModeName(input.permissionMode) ? { permissionMode: input.permissionMode } : {}),+ ...(input.forkedFrom ? { forkedFrom: { agentId: input.forkedFrom.agentId, name: input.forkedFrom.name } } : {}),transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex f985dec26..a637dab2d 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -183,6 +183,25 @@ enum GridWebSearch {}/// Data-plane agent (RPC agents_list).+/// Where a forked agent came from — see [Agent.forkedFrom].+class ForkedFrom {+ final String agentId;+ final String name;++ const ForkedFrom({required this.agentId, required this.name});++ static ForkedFrom? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final agentId = raw['agentId'];+ if (agentId is! String || agentId.isEmpty) return null;+ final name = raw['name'];+ return ForkedFrom(+ agentId: agentId,+ name: name is String && name.isNotEmpty ? name : 'an agent',+ );+ }+}+class Agent {final String id;final String? sessionId;@@ -242,6 +261,16 @@ class Agent {/// The harness's last verdict on this workspace, or null when it has not written one.final AgentVerdict? verdict;+ /// The agent this one was forked from (`agent_fork`), or null for every+ /// other agent. Carries the source's name as it was at the fork, because the+ /// source may be renamed or gone by the time the badge is read.+ final ForkedFrom? forkedFrom;++ /// Whether the daemon can fork this agent (`agent_fork`), as it said on the+ /// frame; null from a daemon that predates the field — then the engine+ /// decides (see [canFork]).+ final bool? forkable;+const Agent({required this.id,this.sessionId,@@ -267,8 +296,21 @@ class Agent {this.viewerError,this.viewerName,this.verdict,+ this.forkedFrom,+ this.forkable,});+ /// The engines whose sessions can be forked — natively (Claude Code's+ /// `--fork-session`, `codex fork`) or by a handoff message (OpenCode takes a+ /// first prompt). The daemon is the authority when it says (`forkable`);+ /// this is the answer for one that does not.+ static const forkableEngines = {'claude', 'codex', 'opencode'};++ /// Whether to offer Fork for this agent at all. Devin, Cursor and the rest+ /// can neither fork nor open with a message, so the button is not drawn+ /// rather than drawn and refused.+ bool get canFork => forkable ?? forkableEngines.contains(engine);+/// What to draw this agent AS: its harness when it has one, else its engine.String? get identityEngine => dsh ?? engine;@@ -330,6 +372,8 @@ class Agent {viewerError: _safeDetail(j['viewerError']),viewerName: _safeLabel(j['viewerName']),verdict: AgentVerdict.fromJson(j['verdict']),+ forkedFrom: ForkedFrom.fromJson(j['forkedFrom']),+ forkable: j['forkable'] is bool ? j['forkable'] as bool : null,);}@@ -358,6 +402,8 @@ class Agent {viewerError: viewerError,viewerName: viewerName,verdict: verdict,+ forkedFrom: forkedFrom,+ forkable: forkable,);/// `owner/name`, exactly the shape the DSH manifest schema allows and nothing else — thediff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex b5527b0ac..18fe113e2 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -86,6 +86,18 @@ class RestartAgentResult {const RestartAgentResult({this.error, this.resumed = true});}+/// Result of [AppNotifier.forkAgent]. [error] null means the fork is open;+/// [level] then says what it got — `native` (the engine's own fork, the whole+/// context) or `handoff` (a first message composed from what the daemon+/// remembers of the source, for an engine that cannot fork).+class ForkAgentResult {+ final String? error;+ final String level;+ final String? agentId;++ const ForkAgentResult({this.error, this.level = 'native', this.agentId});+}+/// One deliberate creation, retained by the form if its reply is lost. Reusing/// it checks the original request; opening New agent starts a fresh intent.class AgentCreationAttempt {@@ -5371,6 +5383,88 @@ class AppNotifier extends ChangeNotifier {return RestartAgentResult(resumed: resumed is bool ? resumed : true);}+ /// Forks an agent via `agent_fork`: a second agent that starts with the+ /// first one's whole history, in the same folder, then goes its own way.+ ///+ /// The fork lands beside its source — in the source's tab when that is the+ /// tab on screen, else in the current tab — and takes focus, because the+ /// person asked for it a moment ago and is about to give it its job. Same+ /// upsert-from-reply rule as [restartAgent].+ Future<ForkAgentResult> forkAgent(+ String machineId,+ String agentId, {+ String? name,+ String? prompt,+ }) async {+ final machine = machineStates[machineId];+ if (machine == null) {+ return const ForkAgentResult(error: 'Machine not found');+ }+ Map<String, dynamic> result;+ try {+ result = await _conn(machineId).request(+ 'agent_fork',+ payload: {+ 'agentId': agentId,+ if (name != null && name.trim().isNotEmpty) 'name': name.trim(),+ if (prompt != null && prompt.trim().isNotEmpty) 'prompt': prompt,+ },+ );+ } catch (error) {+ return ForkAgentResult(error: 'Fork failed: $error');+ }+ final error = result['error'];+ if (error is String) {+ final detail = result['detail'];+ return ForkAgentResult(+ error: detail is String+ ? detail+ : switch (error) {+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>+ 'Update the harness CLI on this machine to fork a harness.',+ 'AGENT_BUSY' => 'This harness is in the middle of a turn. Wait for it to finish, then fork.',+ _ => 'Fork failed: $error',+ },+ );+ }+ final raw = result['agent'];+ if (raw is! Map) return const ForkAgentResult(error: 'Fork failed');+ final Agent fork;+ try {+ fork = Agent.fromJson(Map<String, dynamic>.from(raw));+ } catch (_) {+ return const ForkAgentResult(error: 'Fork failed');+ }+ _upsertAgent(machine, fork);+ notifyListeners();+ await placeFork(machineId, fork.id, sourceAgentId: agentId);+ final level = result['level'];+ return ForkAgentResult(+ level: level is String ? level : 'native',+ agentId: fork.id,+ );+ }++ /// Put a fork on screen beside its source and focus it — the window's half+ /// of a fork asked for here or on the dial (`dial_forked`).+ Future<void> placeFork(+ String machineId,+ String agentId, {+ required String sourceAgentId,+ }) async {+ if (revealAgentView(machineId, agentId)) return;+ // The current tab: it is where the source was forked from, whether by the+ // pane's own menu or by the dial, which shows this tab too. `sourceAgentId`+ // is kept on the wire for a placement that wants the source's tab later.+ assert(sourceAgentId.isEmpty || sourceAgentId != agentId);+ if (activeSwarm.panes.length >= maxPanes) {+ // Beside the source is the wish; a tab of its own is the honest fallback.+ newSwarm();+ }+ await addAgentToSwarm(machineId, agentId, swarmId: activeSwarmId);+ revealAgentView(machineId, agentId);+ }+/// 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@@ -6661,6 +6755,25 @@ class AppNotifier extends ChangeNotifier {final swarmId = payload['swarmId'];if (swarmId is String && swarmId.isNotEmpty) selectSwarm(swarmId);break;+ case 'dial_forked':+ // The dial forked an agent; the daemon already opened the pane on its+ // machine. Land it beside its source and focus it, as the window's own+ // Fork does.+ final forkId = payload['agentId'];+ final forkSource = payload['sourceAgentId'];+ if (forkId is String && forkId.isNotEmpty) {+ final targetMachineId = _dialFocusMachine(payload, forkId);+ if (targetMachineId != null) {+ unawaited(+ placeFork(+ targetMachineId,+ forkId,+ sourceAgentId: forkSource is String ? forkSource : '',+ ),+ );+ }+ }+ break;case 'dial_open':// A notification was tapped on the dial. Unlike `dial_focus` this asks for a tile of its own —// see openAgentFromDial for why a finished turn is not a replacement for what is on screen.diff --git a/desktop/lib/widgets/fork_agent_dialog.dart b/desktop/lib/widgets/fork_agent_dialog.dartnew file mode 100644index 000000000..9d2ccdbd4--- /dev/null+++ b/desktop/lib/widgets/fork_agent_dialog.dart@@ -0,0 +1,249 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';++/// The default name for a fork of [name] — the owner's spelling.+String forkNameFor(String name) =>+ '${name.trim().isEmpty ? 'Agent' : name.trim()} - fork';++/// The engines that can fork a session outright. Fork is only OFFERED for an+/// agent that can fork at all ([Agent.canFork]); among those, this sets the+/// words the dialog opens with, so a person is told before the round trip+/// whether the fork will carry the whole context or a handoff.+const _nativeForkEngines = {'claude', 'codex'};++/// Fork a harness: open the dialog, then a second agent with the first one's+/// history, placed beside it and focused. Errors land as a snackbar; a fork+/// that could only hand off (no native fork on that engine) says so once.+Future<void> forkHarness(+ BuildContext context,+ AppNotifier notifier,+ String machineId,+ String agentId,+ String name, {+ String? engine,+}) async {+ if (notifier.agentIsProcessing(machineId, agentId)) {+ ScaffoldMessenger.of(context).showSnackBar(+ const SnackBar(+ content: Text(+ 'This harness is in the middle of a turn. Wait for it to finish, then fork.',+ ),+ ),+ );+ return;+ }+ final choice = await showForkAgentDialogForTest(+ context,+ name,+ engine: engine,+ );+ if (choice == null || !context.mounted) return;+ final result = await notifier.forkAgent(+ machineId,+ agentId,+ name: choice.name,+ prompt: choice.task,+ );+ if (!context.mounted) return;+ final message =+ result.error ??+ (result.level == 'handoff'+ ? 'Forked with a handoff: this engine cannot copy a session, so the fork opened with a summary of what “$name” had done.'+ : null);+ if (message != null) {+ ScaffoldMessenger.of(context)+ .showSnackBar(SnackBar(content: Text(message)));+ }+}++/// The dialog alone — name and first task, or null on cancel. Public for the+/// widget test; [forkHarness] is what the app calls.+@visibleForTesting+Future<({String name, String task})?> showForkAgentDialogForTest(+ BuildContext context,+ String sourceName, {+ String? engine,+}) => showAppDialog<({String name, String task})>(+ context: context,+ transitionDuration: Duration.zero,+ veilBlur: 0,+ veilTint: const Color(0x99000000),+ builder: (_) => _ForkAgentDialog(sourceName: sourceName, engine: engine),+);++class _ForkAgentDialog extends StatefulWidget {+ const _ForkAgentDialog({required this.sourceName, this.engine});+ final String sourceName;+ final String? engine;+ @override+ State<_ForkAgentDialog> createState() => _ForkAgentDialogState();+}++class _ForkAgentDialogState extends State<_ForkAgentDialog> {+ late final _name = TextEditingController(+ text: forkNameFor(widget.sourceName),+ );+ final _task = TextEditingController();+ final _nameFocus = FocusNode(debugLabel: 'Fork name');+ final _taskFocus = FocusNode(debugLabel: 'Fork first task');++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && ModalRoute.isCurrentOf(context) != false) {+ _taskFocus.requestFocus();+ }+ });+ }++ @override+ void dispose() {+ _nameFocus.dispose();+ _taskFocus.dispose();+ _name.dispose();+ _task.dispose();+ super.dispose();+ }++ void _fork() {+ final name = _name.text.trim();+ if (name.isEmpty) return;+ Navigator.pop(context, (name: name, task: _task.text.trim()));+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final accent = grid.AppPalette.accentOnSurface;+ final border = OutlineInputBorder(+ borderRadius: BorderRadius.circular(10),+ borderSide: BorderSide.none,+ );+ InputDecoration decoration(String hint) => InputDecoration(+ filled: true,+ fillColor: grid.AppSurface.recess,+ isDense: true,+ hintText: hint,+ hintStyle: TextStyle(fontSize: 14, color: grid.AppPalette.textSecondary),+ contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),+ border: border,+ enabledBorder: border,+ focusedBorder: border.copyWith(borderSide: BorderSide(color: accent)),+ counterText: '',+ );+ final native =+ widget.engine == null || _nativeForkEngines.contains(widget.engine);+ final what = native+ ? 'The fork starts with everything “${widget.sourceName}” knows, in the same folder. Both keep running on their own.'+ : 'This engine cannot copy a session: the fork opens with a summary of what “${widget.sourceName}” has done, in the same folder.';+ Widget label(String text) => Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: Text(+ text,+ style: TextStyle(+ fontSize: 12,+ fontWeight: FontWeight.w600,+ color: grid.AppPalette.textSecondary,+ ),+ ),+ );+ return ListenableBuilder(+ listenable: _name,+ builder: (context, _) => AlertDialog(+ title: const Text('Fork Harness'),+ titleTextStyle: Theme.of(context).textTheme.titleMedium,+ content: SizedBox(+ width: 400,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ what,+ style: TextStyle(+ fontFamily: grid.AppFont.sans,+ fontSize: 13,+ height: 1.4,+ color: grid.AppPalette.textSecondary,+ ),+ ),+ const SizedBox(height: 16),+ label('Name'),+ TextField(+ key: const ValueKey('fork-name'),+ controller: _name,+ focusNode: _nameFocus,+ maxLength: 80,+ cursorColor: accent,+ textInputAction: TextInputAction.next,+ style: TextStyle(+ fontSize: 14,+ color: grid.AppPalette.textPrimary,+ ),+ decoration: decoration(''),+ onSubmitted: (_) => _taskFocus.requestFocus(),+ ),+ const SizedBox(height: 14),+ label('First task (optional)'),+ // Return adds a line; ⌘Return forks — the New Harness field's+ // own contract, so the two forms answer the keyboard alike.+ CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.enter, meta: true):+ _fork,+ },+ child: TextField(+ key: const ValueKey('fork-task'),+ controller: _task,+ focusNode: _taskFocus,+ minLines: 2,+ maxLines: 6,+ maxLength: 2000,+ cursorColor: accent,+ style: TextStyle(+ fontSize: 14,+ height: 1.4,+ color: grid.AppPalette.textPrimary,+ ),+ decoration: decoration(+ 'What should the fork work on? Sent as its first message, exactly as written.',+ ),+ ),+ ),+ ],+ ),+ ),+ actions: [+ OutlinedButton(+ onPressed: () => Navigator.pop(context),+ style: OutlinedButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ minimumSize: const Size(88, 38),+ padding: const EdgeInsets.symmetric(horizontal: 18),+ side: const BorderSide(color: Colors.white24),+ shape: const StadiumBorder(),+ ),+ child: const Text('Cancel'),+ ),+ FilledButton(+ key: const ValueKey('fork-submit'),+ onPressed: _name.text.trim().isEmpty ? null : _fork,+ style: FilledButton.styleFrom(+ backgroundColor: grid.AppPalette.swarmAccent,+ foregroundColor: grid.AppPalette.swarmTabBar,+ minimumSize: const Size(88, 38),+ padding: const EdgeInsets.symmetric(horizontal: 18),+ shape: const StadiumBorder(),+ ),+ child: const Text('Fork'),+ ),+ ],+ ),+ );+ }+}diff --git a/desktop/lib/widgets/machine_rail.dart b/desktop/lib/widgets/machine_rail.dartindex 12be9cfea..601b26307 100644--- a/desktop/lib/widgets/machine_rail.dart+++ b/desktop/lib/widgets/machine_rail.dart@@ -18,6 +18,7 @@ import '../state/app_state.dart';import 'agent_drag.dart';import 'machine_actions.dart';import 'delete_agent_dialog.dart';+import 'fork_agent_dialog.dart';import 'restart_agent_action.dart';import 'rename_agent_dialog.dart';import 'account_footer.dart';@@ -1036,6 +1037,15 @@ class _AgentRowState extends State<_AgentRow> {Future<void> _restartAgent() =>restartHarness(context, notifier, state.machine.machineId, agent.id);+ Future<void> _forkAgent() => forkHarness(+ context,+ notifier,+ state.machine.machineId,+ agent.id,+ agent.name,+ engine: agent.engine,+ );+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -1222,6 +1232,15 @@ class _AgentRowState extends State<_AgentRow> {_restartAgent();},),+ if (agent.canFork)+ AppMenuItem(+ icon: LucideIcons.gitFork300,+ label: 'Fork Harness',+ onPressed: () {+ _agentMenu.close();+ _forkAgent();+ },+ ),const AppMenuDivider(),AppMenuItem(icon: Icons.stop_rounded,diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex 0359ae39f..6874c71c2 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -28,6 +28,7 @@ import 'agent_drag.dart';import 'harness_join_guide_screen.dart';import 'new_agent_dialog.dart';import 'delete_agent_dialog.dart';+import 'fork_agent_dialog.dart';import 'restart_agent_action.dart';import 'terminal_panel.dart';import 'web_pane_panel.dart';@@ -1397,6 +1398,16 @@ class _PaneContent extends StatelessWidget {? null: () =>restartHarness(context, notifier, pane.machineId, agent.id),+ onFork: agent == null || offline || needsLink || !agent.canFork+ ? null+ : () => forkHarness(+ context,+ notifier,+ pane.machineId,+ agent.id,+ agent.name,+ engine: agent.engine,+ ),// The same confirmation the rail's row menu opens. Only for an// agent the machine still lists — a pane whose agent is already// gone has nothing to end.diff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dartindex 93253249c..aba057f37 100644--- a/desktop/lib/widgets/pane_header_actions.dart+++ b/desktop/lib/widgets/pane_header_actions.dart@@ -11,6 +11,7 @@ class PaneHeaderActions extends StatelessWidget {required this.zoomed,this.onZoom,this.onRestart,+ this.onFork,this.onShare,this.onDelete,this.onClose,@@ -25,7 +26,12 @@ class PaneHeaderActions extends StatelessWidget {final bool zoomed, composerVisible;final VoidCallback? onShare;- final VoidCallback? onZoom, onRestart, onDelete, onClose, onToggleComposer;+ final VoidCallback? onZoom,+ onRestart,+ onFork,+ onDelete,+ onClose,+ onToggleComposer;/// A harness agent's viewer: show it beside this terminal, or hide it./// Absent for an agent that has no viewer.@@ -127,6 +133,10 @@ class PaneHeaderActions extends StatelessWidget {const SizedBox(width: 2),action('Restart Harness', LucideIcons.refreshCw, onRestart),const SizedBox(width: 2),+ if (onFork != null) ...[+ action('Fork Harness', LucideIcons.gitFork, onFork),+ const SizedBox(width: 2),+ ],action('Stop Harness', Icons.stop_rounded, onDelete),const SizedBox(width: 2),action('Close Pane', LucideIcons.x, onClose),diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 8ef25f098..b12fab1ca 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -49,6 +49,9 @@ class TerminalPanel extends StatefulWidget {/// where there is nothing to close it back to.final VoidCallback? onClose;final VoidCallback? onRestart;++ /// Forks this harness — a second agent with its history (fork_agent_dialog.dart).+ final VoidCallback? onFork;final VoidCallback? onDelete;final VoidCallback? onToggleZoom;@@ -111,6 +114,7 @@ class TerminalPanel extends StatefulWidget {this.onToggleComposer,this.onClose,this.onRestart,+ this.onFork,this.onDelete,this.onToggleZoom,this.zoomed = false,@@ -1387,6 +1391,7 @@ class _TerminalPanelState extends State<TerminalPanel>compact: widget.compactHeader,close: widget.onClose != null,restart: widget.onRestart != null,+ fork: widget.onFork != null,delete: widget.onDelete != null,composer: widget.composerVisible,toggleComposer: widget.onToggleComposer != null,@@ -1411,6 +1416,7 @@ class _TerminalPanelState extends State<TerminalPanel>onRestart: widget.onRestart == null? null: () => widget.onRestart?.call(),+ onFork: widget.onFork == null ? null : () => widget.onFork?.call(),onDelete: widget.onDelete == null? null: () => widget.onDelete?.call(),@@ -1432,6 +1438,7 @@ class _TerminalHeader extends StatelessWidget {final bool readOnly;final VoidCallback? onClose;final VoidCallback? onRestart;+ final VoidCallback? onFork;/// Ends the agent (with a confirmation), as the rail's row menu does. Null/// where the pane cannot name a live agent to end.@@ -1459,6 +1466,7 @@ class _TerminalHeader extends StatelessWidget {this.readOnly = false,this.onClose,this.onRestart,+ this.onFork,this.onDelete,this.compact = false,this.onToggleZoom,@@ -1549,13 +1557,18 @@ class _TerminalHeader extends StatelessWidget {.where((part) => part.isNotEmpty).lastOrNull ??project?.name;+ // A fork says so first: "forked from X" is the one fact about this pane+ // that the folder and the branch — shared with its source — cannot tell.+ final forkedFrom = agent?.forkedFrom;final details = [+ if (forkedFrom != null) 'forked from ${forkedFrom.name}',if (folder?.isNotEmpty == true) folder!,if (project?.branch?.trim().isNotEmpty == true) project!.branch!,machineName,];+ final forkIndex = forkedFrom != null ? 0 : null;final branchIndex = project?.branch?.trim().isNotEmpty == true- ? (folder?.isNotEmpty == true ? 1 : 0)+ ? (forkedFrom != null ? 1 : 0) + (folder?.isNotEmpty == true ? 1 : 0): null;final strip = PaneHeaderHover(child: SizedBox(@@ -1742,6 +1755,7 @@ class _TerminalHeader extends StatelessWidget {zoomed: zoomed,onZoom: onToggleZoom,onRestart: onRestart,+ onFork: onFork,onDelete: onDelete,onClose: onClose,onToggleComposer: remoteComposer,@@ -1763,6 +1777,8 @@ class _TerminalHeader extends StatelessWidget {: agentIdentity(agent).color,details: Tooltip(message: [+ if (forkedFrom != null)+ 'Forked from ${forkedFrom.name}',if (project != null) project.cwd,if (project?.branch?.isNotEmpty == true)'Branch: ${project!.branch}',@@ -1792,6 +1808,14 @@ class _TerminalHeader extends StatelessWidget {),const SizedBox(width: 4),],+ if (i == forkIndex) ...[+ Icon(+ LucideIcons.gitFork300,+ size: 12,+ color: AppColors.mutedStrong,+ ),+ const SizedBox(width: 4),+ ],Flexible(child: Text(details[i],diff --git a/desktop/test/fork_agent_test.dart b/desktop/test/fork_agent_test.dartnew file mode 100644index 000000000..6bcee82c0--- /dev/null+++ b/desktop/test/fork_agent_test.dart@@ -0,0 +1,232 @@+// Fork a harness: the request the app sends, where the fork lands, and what+// the model keeps about it.+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/widgets/fork_agent_dialog.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show createApp;++class _Connection extends WsConn {+ _Connection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final calls = <(String, Map<String, dynamic>)>[];+ Future<Map<String, dynamic>> Function(String type, Map<String, dynamic>)?+ answer;++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) {+ calls.add((type, Map.of(payload)));+ return answer?.call(type, payload) ?? Future.value({});+ }++ @override+ Future<void> connect() async {}+}++Map<String, dynamic> _agentJson(+ String id, {+ Map<String, dynamic>? forkedFrom,+}) => {+ 'id': id,+ 'name': id,+ 'engine': 'claude',+ 'status': 'active',+ 'terminal': {'available': true, 'primary': '', 'runtimes': []},+ 'forkedFrom': forkedFrom,+};++void main() {+ test(+ 'the model keeps where a fork came from, and nothing for other agents',+ () {+ final fork = Agent.fromJson(+ _agentJson('f', forkedFrom: {'agentId': 'a0', 'name': 'Kinh Te'}),+ );+ expect(fork.forkedFrom?.agentId, 'a0');+ expect(fork.forkedFrom?.name, 'Kinh Te');+ expect(fork.copyWith(name: 'x').forkedFrom?.agentId, 'a0');+ expect(Agent.fromJson(_agentJson('a')).forkedFrom, isNull);+ // A row with an id and no name still says it is a fork.+ expect(+ Agent.fromJson(_agentJson('g', forkedFrom: {'agentId': 'a0'}))+ .forkedFrom+ ?.name,+ 'an agent',+ );+ },+ );++ test('forkAgent sends agent_fork with the name and task, then lands the fork beside its source', () async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ connection.answer = (type, payload) async {+ if (type == 'agent_fork') {+ return {+ 'agent': _agentJson(+ 'a0-fork',+ forkedFrom: {'agentId': 'a0', 'name': 'Agent 0'},+ ),+ 'level': 'native',+ };+ }+ return {};+ };+ await app.addAgentToSwarm('m', 'a0');+ expect(app.activeSwarm.panes.map((p) => p.agentId), ['a0']);++ final result = await app.forkAgent(+ 'm',+ 'a0',+ name: 'Agent 0 - fork',+ prompt: 'ship it',+ );+ expect(result.error, isNull);+ expect(result.level, 'native');+ expect(result.agentId, 'a0-fork');+ final call = connection.calls.firstWhere((c) => c.$1 == 'agent_fork');+ expect(call.$2, {+ 'agentId': 'a0',+ 'name': 'Agent 0 - fork',+ 'prompt': 'ship it',+ });++ // Beside the source, in the tab that was open, focused, and known to the machine.+ expect(app.activeSwarm.panes.map((p) => p.agentId), ['a0', 'a0-fork']);+ expect(app.focusedPane?.agentId, 'a0-fork');+ expect(+ app.machineStates['m']!.agents.any((a) => a.id == 'a0-fork'),+ isTrue,+ );+ });++ test('a refusal comes back as words, and nothing is placed', () async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ connection.answer = (type, payload) async => {+ 'error': 'AGENT_BUSY',+ 'detail': 'Wait for it to finish, then fork.',+ };+ await app.addAgentToSwarm('m', 'a0');+ final result = await app.forkAgent('m', 'a0');+ expect(result.error, 'Wait for it to finish, then fork.');+ expect(app.activeSwarm.panes.map((p) => p.agentId), ['a0']);+ // An older daemon has no word for it; the app says what to do.+ connection.answer = (type, payload) async => {+ 'error': 'UNSUPPORTED_ON_REMOTE',+ };+ expect(+ (await app.forkAgent('m', 'a0')).error,+ contains('Update the harness CLI'),+ );+ });++ test('a dial_forked push lands the fork the same way', () async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ app.machineStates['m']!.agents.add(+ Agent.fromJson(+ _agentJson('a0-fork', forkedFrom: {'agentId': 'a0', 'name': 'Agent 0'}),+ ),+ );+ await app.handleEventForTest('m', {+ 'type': 'dial_forked',+ 'payload': {+ 'machineId': 'm',+ 'agentId': 'a0-fork',+ 'sourceAgentId': 'a0',+ },+ });+ await Future<void>.delayed(Duration.zero);+ expect(app.activeSwarm.panes.map((p) => p.agentId), ['a0', 'a0-fork']);+ expect(app.focusedPane?.agentId, 'a0-fork');+ });++ testWidgets(+ 'the dialog opens named "X - fork", takes a task, and ⌘Return forks',+ (tester) async {+ ({String name, String task})? picked;+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => TextButton(+ onPressed: () async {+ picked = await showForkAgentDialogForTest(+ context,+ 'Kinh Te',+ engine: 'claude',+ );+ },+ child: const Text('open'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('open'));+ await tester.pumpAndSettle();+ expect(find.text('Fork Harness'), findsOneWidget);+ expect(find.textContaining('everything “Kinh Te” knows'), findsOneWidget);+ final name = tester.widget<TextField>(+ find.byKey(const ValueKey('fork-name')),+ );+ expect(name.controller!.text, 'Kinh Te - fork');+ await tester.enterText(+ find.byKey(const ValueKey('fork-task')),+ 'ship it',+ );+ await tester.tap(find.byKey(const ValueKey('fork-submit')));+ await tester.pumpAndSettle();+ expect(picked, (name: 'Kinh Te - fork', task: 'ship it'));+ },+ );++ test('Fork is offered only where the daemon (or the engine) can fork', () {+ expect(+ Agent.fromJson({..._agentJson('a'), 'forkable': false}).canFork,+ isFalse,+ );+ expect(+ Agent.fromJson({..._agentJson('a'), 'forkable': true, 'engine': 'devin'})+ .canFork,+ isTrue,+ );+ // An older daemon says nothing: the engine decides.+ expect(+ Agent.fromJson({..._agentJson('a'), 'engine': 'devin'}).canFork,+ isFalse,+ );+ expect(+ Agent.fromJson({..._agentJson('a'), 'engine': 'codex'}).canFork,+ isTrue,+ );+ expect(+ Agent.fromJson({..._agentJson('a'), 'engine': 'opencode'}).canFork,+ isTrue,+ );+ });++ test('forkNameFor is the source name with " - fork"', () {+ expect(forkNameFor('Kinh Te'), 'Kinh Te - fork');+ expect(forkNameFor(' '), 'Agent - fork');+ });+}diff --git a/devices/harness-device/firmware/main/cable_client.c b/devices/harness-device/firmware/main/cable_client.cindex 8fadcafaa..9eb6c0e3c 100644--- a/devices/harness-device/firmware/main/cable_client.c+++ b/devices/harness-device/firmware/main/cable_client.c@@ -176,6 +176,15 @@ void cable_client_send_focus(const char *agent_id)send_json(root);}+void cable_client_send_fork(const char *agent_id)+{+ if (!agent_id || !agent_id[0]) return;+ cJSON *root = msg("agent.fork");+ if (!root) return;+ cJSON_AddStringToObject(root, "agentId", agent_id);+ send_json(root);+}+void cable_client_send_open(const char *agent_id){if (!agent_id || !agent_id[0]) return;diff --git a/devices/harness-device/firmware/main/cable_client.h b/devices/harness-device/firmware/main/cable_client.hindex 0d9c117ab..093cb82cf 100644--- a/devices/harness-device/firmware/main/cable_client.h+++ b/devices/harness-device/firmware/main/cable_client.h@@ -172,6 +172,9 @@ void cable_client_send_focus(const char *agent_id);// of its own, because the turn that just finished is a new thing to look at, not a replacement for what// the person was already watching. The window opens a new one, or reuses its last when the grid is full.void cable_client_send_open(const char *agent_id);+// Ask for a FORK of this agent: a second one with its whole history, which the daemon opens in the window+// beside it. The dial hears back only on refusal (a `toast`).+void cable_client_send_fork(const char *agent_id);// One report of a finger on the glass, on its way to the window on the computer.//diff --git a/devices/harness-device/firmware/main/ui/ui_screens.c b/devices/harness-device/firmware/main/ui/ui_screens.cindex 11265ecf4..4a8353710 100644--- a/devices/harness-device/firmware/main/ui/ui_screens.c+++ b/devices/harness-device/firmware/main/ui/ui_screens.c@@ -116,6 +116,7 @@ extern const lv_font_t geist_sem_24; // largest display: tile agent name + over#define COL_RED lv_color_hex(0xff5a5a)#define COL_ACCENT lv_color_hex(0x5b8cff)#define COL_YELLOW lv_color_hex(0xf0b429)+#define COL_FORK lv_color_hex(0x5b8cff) // the Loop mark's blue, now the Fork mark's — same arc, same slot#define COL_ORANGE lv_color_hex(0xff8a4c) // working-status verb row#define COL_CLAUDE lv_color_hex(0xcc7c5e) // matches the shared Claude reference color#define COL_CARD lv_color_hex(0x16161c)@@ -233,7 +234,7 @@ static lv_obj_t *s_settings_tile; // the extra tile at column == s_proj_countstatic lv_obj_t *s_agent_acts;// The three round marks on the bottom arc of an agent tile. Held individually because touch.c has to be// able to ask whether a press landed on one — see ui_action_hit().-static lv_obj_t *s_agent_goal_btn, *s_agent_voice_btn, *s_agent_loop_btn;+static lv_obj_t *s_agent_goal_btn, *s_agent_voice_btn, *s_agent_loop_btn, *s_agent_fork_btn;#define AGENT_TILE_GOAL_LOOP 0 // the Goal and Loop marks beside Voice on an agent tile — see build_agent_actionsstatic lv_obj_t *s_machines_tile; // Machines carousel tile (ring 1, between Settings and the agents)static lv_obj_t *s_no_agents_tile; // persistent "No agents yet" page, shown at ring RING_LEAD ONLY when s_proj_count==0@@ -400,7 +401,8 @@ static void cancel_confirm_no(lv_event_t *e); // "Cancel task?" No → dismiss,static void stop_event(lv_event_t *e); // tap STOP → cancel the active turn (defined below)static void update_stop_btn(void); // show/hide STOP per active tile's processing state (caller holds lock)-static void agent_actions_apply(void); // show/hide the per-agent Goal/Voice/Loop cluster (caller holds lock)+static void agent_actions_apply(void); // show/hide the per-agent Voice/Fork cluster (caller holds lock)+static void machine_toast(const char *msg); // a short centred line over the face (defined with the machine picker)static void build_agent_actions(void); // build that cluster once on scr_projects (defined below)static void notif_badge_apply(void); // show/hide the top unread pill (defined below)static void notif_bg_tap(lv_event_t *e); // tap the drawer's empty area → close (defined below)@@ -2965,6 +2967,20 @@ static void agent_voice_tap(lv_event_t *e)s_suppress_tap = true; // this press started a capture; it must not also land as a tap on the tilevoice_start_impl(VOICE_CMD_NONE);}+// Fork — a second agent with this one's whole history, opened in the window beside it (owner,+// 2026-09-18). The daemon does the work (`agent.fork` → lib/forkAgent.ts) and tells the window; the dial+// only hears back when it was refused, as a toast. Said out loud here so a press that will take a few+// seconds to show anything is not a press that felt lost.+static void agent_fork_tap(lv_event_t *e)+{+ (void)e;+ if (!agent_action_ready()) return;+ s_suppress_tap = true;+ const char *id = s_proj[s_active_idx].id;+ if (s_proj[s_active_idx].busy_model) { machine_toast("Wait for the turn to finish, then fork"); return; }+ cable_client_send_fork(id);+ machine_toast("Forking\xE2\x80\xA6");+}static __attribute__((unused)) void agent_goal_tap (lv_event_t *e) { (void)e; if (agent_action_ready()) voice_start_impl(VOICE_CMD_GOAL); }static __attribute__((unused)) void agent_loop_tap (lv_event_t *e) { (void)e; if (agent_action_ready()) voice_start_impl(VOICE_CMD_LOOP); }@@ -2981,6 +2997,14 @@ static void agent_actions_apply(void)&& !s_machines_active && !s_notif_open && !display_is_asleep()&& s_active_idx >= 0 && s_active_idx < s_proj_count;set_hidden(s_agent_acts, !on);+ // Fork only where a fork can be anything (owner, 2026-09-18: "chỉ hiện fork cho agent có khả năng+ // fork như claude/codex"): Claude Code and Codex fork natively, OpenCode takes a handoff message;+ // Devin, Cursor and the rest can do neither, and a button that only refuses is not drawn.+ if (s_agent_fork_btn && on) {+ const char *eng = s_proj[s_active_idx].engine;+ bool forkable = strcmp(eng, "claude") == 0 || strcmp(eng, "codex") == 0 || strcmp(eng, "opencode") == 0;+ set_hidden(s_agent_fork_btn, !forkable);+ }}static lv_obj_t *agent_act_btn(int32_t x, int32_t y, lv_event_cb_t cb)@@ -3066,6 +3090,39 @@ static void build_agent_actions(void)lv_obj_t *ic = lv_image_create(b);lv_image_set_src(ic, &icon_act_voice); // 44px native, colour baked — see the note on the assetlv_obj_center(ic); }+ // Fork — where Loop used to sit (the right end of the arc, 307/322), drawn from plain objects like Goal+ // was: two dots on top and one below, joined — the git-fork mark every tab and pane header wears for+ // a forked harness. Objects rather than an image for the reason the note above gives about images+ // on the tile that is on screen most of the time.+ { lv_obj_t *b = agent_act_btn(307, 322, agent_fork_tap);+ s_agent_fork_btn = b;+ lv_obj_t *g = lv_obj_create(b);+ lv_obj_remove_style_all(g);+ lv_obj_clear_flag(g, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);+ lv_obj_set_size(g, 44, 44);+ lv_obj_center(g);+ static const lv_point_precise_t left[] = { { 9, 11 }, { 9, 18 }, { 22, 26 }, { 22, 34 } };+ static const lv_point_precise_t right[] = { { 35, 11 }, { 35, 18 }, { 22, 26 } };+ const lv_point_precise_t *strokes[] = { left, right };+ const int counts[] = { 4, 3 };+ for (int k = 0; k < 2; k++) {+ lv_obj_t *ln = lv_line_create(g);+ lv_line_set_points(ln, strokes[k], counts[k]);+ lv_obj_set_style_line_width(ln, 4, 0);+ lv_obj_set_style_line_color(ln, COL_FORK, 0);+ lv_obj_set_style_line_rounded(ln, true, 0);+ }+ const int dots[][2] = { { 9, 8 }, { 35, 8 }, { 22, 37 } };+ for (int k = 0; k < 3; k++) {+ lv_obj_t *c = lv_obj_create(g);+ lv_obj_remove_style_all(c);+ lv_obj_clear_flag(c, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);+ lv_obj_set_size(c, 12, 12);+ lv_obj_set_pos(c, dots[k][0] - 6, dots[k][1] - 6);+ lv_obj_set_style_radius(c, LV_RADIUS_CIRCLE, 0);+ lv_obj_set_style_bg_color(c, COL_FORK, 0);+ lv_obj_set_style_bg_opa(c, LV_OPA_COVER, 0);+ } }#if AGENT_TILE_GOAL_LOOP// Loop — the exported Figma repeat arrows, the same mark the Overview carries, and the mirror of Goal's// 20px push: 287 → 307.@@ -3125,6 +3182,7 @@ bool ui_action_hit(uint16_t x, uint16_t y)if (s_agent_acts && !lv_obj_has_flag(s_agent_acts, LV_OBJ_FLAG_HIDDEN)) {if ((s_agent_goal_btn && lv_obj_hit_test(s_agent_goal_btn, &pt)) ||(s_agent_voice_btn && lv_obj_hit_test(s_agent_voice_btn, &pt)) ||+ (s_agent_fork_btn && lv_obj_hit_test(s_agent_fork_btn, &pt)) ||(s_agent_loop_btn && lv_obj_hit_test(s_agent_loop_btn, &pt))) return true;}@@ -5399,6 +5457,7 @@ void ui_project_set_engine(const char *project_id, const char *engine)if (valid) snprintf(s_proj[i].engine, sizeof(s_proj[i].engine), "%s", valid);else s_proj[i].engine[0] = '\0';apply_engine_label(&s_proj[i]);+ if (i == s_active_idx) agent_actions_apply(); // the Fork mark follows the engine}display_unlock();}@@ -6851,7 +6910,6 @@ static EXT_RAM_BSS_ATTR struct {} s_q;static void q_render(void);-static void machine_toast(const char *msg); // defined with the machine picker, belowstatic void q_advance(void);static void q_cancel(void);static void q_opt_tap(lv_event_t *e);