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
Take over a conversation open in a terminal (#385)
Dee71ee60f874fb
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 0881c77c4..34cc56471 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -1081,7 +1081,7 @@ describe('BackendSocket outbound queue', () => {socket.registerLocalClient('local:resume', {sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,})- const inputs: Array<{ resumeSessionId?: string | null; cwd: string }> = []+ const inputs: Array<{ resumeSessionId?: string | null; takeOver?: string | null; cwd: string }> = []socket.onCreateAgent = async (input) => {inputs.push(input)return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: 'It is open in another terminal or app.' }@@ -1095,12 +1095,17 @@ describe('BackendSocket outbound queue', () => {expect(inputs[0]).toMatchObject({ resumeSessionId: '01a0c4ad-de5e-7000-8000-000000000001', cwd: '/work/cohorts' })// What cli.ts said about it reaches the client as it was said.expect(reply('ok')).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE', detail: 'It is open in another terminal or app.' })+ // Taken over from the terminal that has it: how, passed on as asked.+ create('wait', { resumeSessionId: '01a0c4ad-de5e-7000-8000-000000000001', takeOver: 'wait' })+ await vi.waitFor(() => expect(reply('wait')).toBeDefined())+ expect(inputs[1]).toMatchObject({ takeOver: 'wait' })create('shape', { resumeSessionId: '../../etc/passwd' })create('prompt', { resumeSessionId: '01a0c4ad-de5e-7000-8000-000000000001', prompt: 'and then this' })- await vi.waitFor(() => expect(reply('prompt')).toBeDefined())- expect(reply('shape')).toMatchObject({ error: 'INVALID_SESSION' })- expect(reply('prompt')).toMatchObject({ error: 'INVALID_SESSION' })- expect(inputs).toHaveLength(1)+ create('how', { resumeSessionId: '01a0c4ad-de5e-7000-8000-000000000001', takeOver: 'forcefully' })+ create('what', { takeOver: 'now' })+ await vi.waitFor(() => expect(reply('what')).toBeDefined())+ for (const id of ['shape', 'prompt', 'how', 'what']) expect(reply(id)).toMatchObject({ error: 'INVALID_SESSION' })+ expect(inputs).toHaveLength(2)await socket.unregisterLocalClient('local:resume')await socket.stop()})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 234da8798..2202cfb8c 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -497,6 +497,10 @@ export class BackendSocket {* folder (lib/sessionSearch/external.ts). Null for a new conversation. Shape-checked here; cli.ts* checks it is one it found, not open elsewhere, and not already a harness. */resumeSessionId?: string | null+ /** A conversation open in a terminal, taken over from it: `idle` stops that terminal's process+ * only between turns, `now` whatever it is doing (then tells it to continue), `wait` when its+ * turn ends. Absent, one open elsewhere is refused and the refusal says whether it is busy. */+ takeOver?: 'idle' | 'now' | 'wait' | null}) =>Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null/** Called on `dsh_install` — cli.ts clones/sets up/doctors the harness and reports each phase. */@@ -2354,6 +2358,13 @@ export class BackendSocket {}resumeSessionId = payload.resumeSessionId}+ let takeOver: 'idle' | 'now' | 'wait' | null = null+ if (payload.takeOver !== undefined && payload.takeOver !== null) {+ if (!resumeSessionId || (payload.takeOver !== 'idle' && payload.takeOver !== 'now' && payload.takeOver !== 'wait')) {+ reply(type, requestId, { error: 'INVALID_SESSION', detail: 'takeOver is idle, now or wait, with a resumeSessionId' }); return+ }+ takeOver = payload.takeOver+ }const input = {engine,cwd: typeof cwd === 'string' ? cwd : terminal ? homedir() : '',@@ -2367,6 +2378,7 @@ export class BackendSocket {name,agent,resumeSessionId,+ takeOver,}const fingerprintInput = model.state === 'ok' ? { ...input, modelSelection: model.selection } : inputif (creationId !== undefined) {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 508a31c1c..2f86b4f62 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -94,7 +94,7 @@ import { createRetainExitedSession } from './lib/retainExitedSession.js'import { repairClaudeCwd } from './lib/cwdRepair.js'import { stoppedAgents } from './lib/stoppedAgents.js'import { SessionSearchIndex, folderWords, type SearchSource } from './lib/sessionSearch/indexer.js'-import { ExternalSessions, OpenSessions } from './lib/sessionSearch/external.js'+import { ExternalSessions, OpenSessions, processAlive, sessionBusy, stopSessionOwner, type SessionOwner } from './lib/sessionSearch/external.js'import { SessionSearchStore } from './lib/sessionSearch/store.js'import { SESSION_SEARCH_FILE, searchCommand } from './lib/sessionSearch/command.js'import { sweepWorktrees } from './lib/worktreeSweep.js'@@ -4889,8 +4889,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {* 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 watchNewPane = async (engine: AgentEngine, pending: RegisteredSession, spawned: { runtime: TmuxRuntimeRef }, command: string[], installIfMissing: ReturnType<typeof engineInstallRecipe> | undefined, budgetMs = 10 * 60_000): Promise<void> => {const startedAt = Date.now()let delayMs = 50try {@@ -4968,7 +4967,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {})delayMs = Math.min(delayMs * 2, 750)}- const detail = `${engine} did not expose an engine process within 10 minutes. The terminal remains available.`+ const detail = `${engine} did not expose an engine process within ${Math.round(budgetMs / 60_000)} 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}`)@@ -4981,32 +4980,70 @@ async function runForeground(session: AuthSession | null): Promise<void> {* Whether a conversation Harness did not start can be opened here as a harness: one discovery found* (looked for again if it is new), on this engine, not already a harness, and not open in a running* process — a terminal or the engine's app that still has it would write it too.+ *+ * One open in a terminal can be taken over ([takeOver]): the terminal's process is stopped and the+ * conversation resumes here. Asked without it, the refusal says whether that process is mid-turn,+ * so the person can choose to wait for the turn to end or stop it now. An app's is never stopped.*/- const adoptableSession = async (sessionId: string, engine: AgentEngine): Promise<{ ok: true; cwd: string; title: string } | { ok: false; error: string; detail: string }> => {+ const adoptableSession = async (sessionId: string, engine: AgentEngine, takeOver: 'idle' | 'now' | 'wait' | null): Promise<{ ok: true; cwd: string; title: string; owner: SessionOwner | null; busy: boolean } | { ok: false; error: string; detail: string }> => {if (registry.bySession(sessionId) || stoppedAgents.list().some((s) => s.sessionId === sessionId)) {return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }}const found = externalSessions.get(sessionId) ?? (await externalSessions.scan(), externalSessions.get(sessionId))if (!found) return { ok: false, error: 'SESSION_NOT_FOUND', detail: 'This conversation is no longer on this machine.' }if (found.engine !== engine) return { ok: false, error: 'INVALID_ENGINE', detail: `This is a ${found.engine} conversation.` }- if ((await openSessions.fresh()).has(sessionId)) {- return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: 'It is open in another terminal or app. Close it there, then open it here.' }- }- // The Codex app keeps a thread in a folder of its own, which people tidy away.+ // The Codex app keeps a thread in a folder of its own, which people tidy away. Checked before+ // anything is stopped: a take-over that then cannot open would only have closed it.if (!existsSync(found.cwd)) {return { ok: false, error: 'SESSION_FOLDER_GONE', detail: `The folder it ran in is gone: ${found.cwd}` }}- return { ok: true, cwd: found.cwd, title: found.title || sessionSearch?.session(sessionId)?.title || '' }+ const title = found.title || sessionSearch?.session(sessionId)?.title || ''+ const owner = await openSessions.owner(sessionId)+ if (!owner) return { ok: true, cwd: found.cwd, title, owner: null, busy: false }+ const engineName = engine === 'claude' ? 'Claude Code' : 'Codex'+ if (!owner.tty) {+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It is open in the ${engine === 'claude' ? 'Claude' : 'Codex'} app. Close it there, then open it here.` }+ }+ const busy = await sessionBusy(owner)+ if (busy && (takeOver === null || takeOver === 'idle')) {+ return { ok: false, error: 'SESSION_BUSY_IN_TERMINAL', detail: `${engineName} is working on it in a terminal.` }+ }+ if (takeOver === null) {+ return { ok: false, error: 'SESSION_OPEN_IN_TERMINAL', detail: `It is open in ${engineName} in a terminal. Moving it here quits it there.` }+ }+ return { ok: true, cwd: found.cwd, title, owner, busy }+ }++ /**+ * A conversation taken over when its turn ends (`takeOver: 'wait'`): its pane waits for the+ * terminal's process to go (engineLaunch `waitForPid`), and this stops that process once the turn+ * is over. It gives up when the harness does — closed, or Ctrl-C in its pane — and when the person+ * quits it in the terminal themselves, which is the pane's cue as well.+ */+ const takeOverWhenIdle = async (agentId: string, owner: SessionOwner, sessionId: string): Promise<void> => {+ for (;;) {+ await new Promise<void>((resolve) => { const timer = setTimeout(resolve, 1_000); timer.unref?.() })+ if (registry.byAgent(agentId)?.launch?.state !== 'starting' || !processAlive(owner.pid)) return+ if (await sessionBusy(owner)) continue+ const stopped = await stopSessionOwner(owner)+ console.log(`[agent] take over ${sid(sessionId)} · turn ended · pid ${owner.pid} ${stopped ? 'stopped' : 'did not stop'}`)+ return+ }}- backend.onCreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId }) => {+ backend.onCreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId, takeOver }) => {if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }- // A conversation Harness did not start opens in its own folder, under its own title.+ // A conversation Harness did not start opens in its own folder, under its own title — taken over+ // from the terminal that has it, when asked to.+ let owner: SessionOwner | null = null+ let ownerBusy = falseif (resumeSessionId) {- const adopted = await adoptableSession(resumeSessionId, engine)+ const adopted = await adoptableSession(resumeSessionId, engine, takeOver ?? null)if (!adopted.ok) return adoptedcwd = adopted.cwdname = name ?? (adopted.title || null)+ owner = adopted.owner+ ownerBusy = adopted.busy}try {if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }@@ -5149,7 +5186,18 @@ async function runForeground(session: AuthSession | null): Promise<void> {const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent) : [])]// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).- const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(prompt ? { firstPrompt: prompt } : {}), ...(resumeSessionId ? { resumeSessionId } : {}), terminalHint: { machineName: terminalHintMachineName() } }+ // The terminal's process goes last, once nothing else here can refuse the launch: stopped now, or+ // — to wait for its turn — left running for the pane to wait on. Stopped mid-turn, the resumed+ // conversation is told to carry on.+ const waitFor = owner && takeOver === 'wait' && ownerBusy ? owner : null+ if (owner && !waitFor) {+ if (!await stopSessionOwner(owner)) {+ return { ok: false, error: 'SESSION_STOP_FAILED', detail: 'The terminal that has it did not quit. Close it there, then open it here.' }+ }+ console.log(`[agent] take over ${sid(resumeSessionId ?? '')} · pid ${owner.pid} stopped${ownerBusy ? ' mid-turn' : ''}`)+ }+ const firstPrompt = prompt ?? (owner && !waitFor && ownerBusy ? 'continue' : null)+ const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), ...(resumeSessionId ? { resumeSessionId } : {}), ...(waitFor ? { waitForPid: { pid: waitFor.pid, name: engine === 'claude' ? 'Claude Code' : 'Codex' } } : {}), terminalHint: { machineName: terminalHintMachineName() } }const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)// A tmux route is enough to stream its screen. Register it before looking for a process so both@@ -5197,7 +5245,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {announceSession(pending)if (pending.dsh) attachDsh(pending)- void watchNewPane(engine, pending, spawned, command, installIfMissing)+ // A pane waiting out another terminal's turn may wait as long as that turn takes.+ void watchNewPane(engine, pending, spawned, command, installIfMissing, waitFor ? 24 * 60 * 60_000 : undefined)+ if (waitFor && resumeSessionId) void takeOverWhenIdle(pending.agentId, waitFor, resumeSessionId)console.log(`[agent] create pane open · ${engine} · agent ${pending.agentId}`)return { ok: true, session: pending }}diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex fe858a04a..e080482da 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -106,6 +106,26 @@ describe('buildEngineLaunchArgv', () => {// No shell was handed over and no "this pane is a shell now" line was printed: no tty.expect(result.out).not.toContain('This pane is a shell now')})+ it('a take-over that waits says so, and starts the engine only once the other process is gone', () => {+ // Not a child of this process, as the terminal's is not: an unreaped child never looks gone.+ const pid = Number(execFileSync('/bin/sh', ['-c', 'sleep 1 >/dev/null 2>&1 & echo $!']).toString().trim())+ try {+ const argv = buildEngineLaunchArgv('codex', { waitForPid: { pid, name: 'Codex' } }, '/bin/sh', undefined, undefined, NO_TMUX)+ const started = Date.now()+ const result = run([argv[0], argv[1], argv[2], 'harness-engine', '/bin/sh', '-c', 'printf "%s\\n" "engine ran"'])+ expect(Date.now() - started).toBeGreaterThanOrEqual(800)+ expect(result.out).toContain('Waiting for the Codex in your terminal to finish its turn.')+ expect(result.out.indexOf('Waiting for')).toBeLessThan(result.out.indexOf('engine ran'))+ expect(result.status).toBe(0)+ } finally {+ try { process.kill(pid) } catch { /* gone */ }+ }+ // Nothing to wait for: it starts at once.+ const argv = buildEngineLaunchArgv('codex', { waitForPid: { pid: 2 ** 22 + 7, name: 'Codex' } }, '/bin/sh', undefined, undefined, NO_TMUX)+ const started = Date.now()+ expect(run([argv[0], argv[1], argv[2], 'harness-engine', '/bin/sh', '-c', 'printf "%s\\n" "engine ran"']).out).toContain('engine ran')+ expect(Date.now() - started).toBeLessThan(800)+ })it('a command that does not exist still ends the pane with 127, so "not installed" stays a launch failure', () => {const argv = buildEngineLaunchArgv('claude', {}, '/bin/sh', undefined, undefined, NO_TMUX)expect(run([argv[0], argv[1], argv[2], 'harness-engine', '/nowhere/claude-that-is-not-here']).status).toBe(127)diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex 92e4b5a31..72db30249 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -264,6 +264,13 @@ export interface LaunchCommandOptions {harnessNode?: boolean/** Workspace entered after interactive-shell startup, not before it. */cwd?: string+ /**+ * A conversation taken over from the terminal that has it, once its turn ends (`agent_create`+ * `takeOver: 'wait'`): the pane says it is waiting and starts the engine when that process is+ * gone — the daemon stops it when the turn ends. Ctrl-C gives up and leaves it where it was.+ * Ignored without an interactive shell, like `installFirst`: there is no script to wait in.+ */+ waitForPid?: { pid: number; name: string }}/**@@ -435,7 +442,19 @@ export function buildEngineLaunchArgv(// SERVER's soft limit, which is launchd's 256 whenever the desktop app started the daemon that// started the server, and an engine (Claude Code refuses outright) or an npm install under 256 is// the failure the person then reads in the pane. See openFiles.ts.- return [interactive.path, ...interactive.args, RAISE_OPEN_FILES_SH + prelude + cwdPrelude + body, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command]+ const wait = opts.waitForPid ? waitForPidScript(opts.waitForPid) : ''+ return [interactive.path, ...interactive.args, RAISE_OPEN_FILES_SH + prelude + cwdPrelude + wait + body, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command]+}++/** Waits in the pane for [wait]'s process to end before the engine starts: see `waitForPid`. */+function waitForPidScript(wait: { pid: number; name: string }): string {+ const pid = Math.trunc(wait.pid)+ const name = wait.name.replace(/[^A-Za-z0-9 ._-]/g, '')+ return `printf '%s\\n' 'Waiting for the ${name} in your terminal to finish its turn.' 'It moves here when the turn ends. Ctrl-C leaves it there.'\n`+ + `trap 'printf "\\n%s\\n" "It stays in your terminal."; exit 130' INT\n`+ + `while kill -0 ${pid} 2>/dev/null; do sleep 1; done\n`+ + `trap - INT\n`+ + `printf '\\033[H\\033[2J'\n`}/**diff --git a/cli/src/lib/sessionSearch/external.spec.ts b/cli/src/lib/sessionSearch/external.spec.tsindex 0432782fe..00c346012 100644--- a/cli/src/lib/sessionSearch/external.spec.ts+++ b/cli/src/lib/sessionSearch/external.spec.ts@@ -4,7 +4,7 @@ import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'-import { ExternalSessions, OpenSessions, readClaudeHead, readCodexHead } from './external.js'+import { ExternalSessions, OpenSessions, readClaudeHead, readCodexHead, sessionBusy, stopSessionOwner } from './external.js'const dirs: string[] = []afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })@@ -98,7 +98,9 @@ describe('ExternalSessions', () => {})describe('OpenSessions', () => {- it('knows Claude sessions from their live process records, and Codex ones from open rollouts', async () => {+ const rollout = (id: string) => `/h/.codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-${id}.jsonl`++ it('knows Claude sessions from their live process records, Codex ones from open rollouts, and which are in a terminal', async () => {const root = home()write(join(root, 'sessions', '101.json'), [{ pid: 101, sessionId: A }])write(join(root, 'sessions', '102.json'), [{ pid: 102, sessionId: B }])@@ -108,13 +110,14 @@ describe('OpenSessions', () => {const open = new OpenSessions({claudeHome: root,alive: (pid) => pid === 101,- openRollouts: async () => { reads++; return [`/h/.codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-${C}.jsonl`] },+ openRollouts: async () => { reads++; return [{ pid: 201, path: rollout(C) }] },+ ttys: async (pids) => new Map(pids.map((pid) => [pid, pid === 101 ? '/dev/ttys003' : null])),now: () => now,maxAgeMs: 5_000,})expect(open.known().size).toBe(0)const ids = await open.fresh()- expect([...ids].sort()).toEqual([A, C].sort())+ expect([...ids].sort()).toEqual([[A, 'terminal'], [C, 'app']].sort())expect(reads).toBe(1)now += 1_000await open.fresh()@@ -122,6 +125,54 @@ describe('OpenSessions', () => {now += 10_000await open.fresh()expect(reads).toBe(2)- expect(open.known().has(C)).toBe(true)+ expect(open.known().get(C)).toBe('app')+ // Who has one is looked at now, not taken from the last answer.+ expect(await open.owner(A)).toEqual({ pid: 101, engine: 'claude', tty: '/dev/ttys003', record: join(root, 'sessions', '101.json') })+ expect(reads).toBe(3)+ expect(await open.owner(B)).toBeNull()+ })+})++describe('sessionBusy', () => {+ it("reads Claude Code's record, and where the last Codex turn in the rollout stands", async () => {+ const dir = home()+ const claude = (status: string) => ({ engine: 'claude' as const, record: write(join(dir, `${status}.json`), [{ pid: 1, sessionId: A, status }]) })+ expect(await sessionBusy(claude('idle'))).toBe(false)+ expect(await sessionBusy(claude('busy'))).toBe(true)+ expect(await sessionBusy({ engine: 'claude', record: join(dir, 'gone.json') })).toBe(false)++ const event = (type: string) => ({ type: 'event_msg', payload: { type } })+ const codex = (name: string, lines: unknown[]) => ({ engine: 'codex' as const, record: write(join(dir, `${name}.jsonl`), [codexMeta(C, 'cli'), ...lines]) })+ // What was said can name the events; only the events count.+ const talk = { type: 'response_item', payload: { type: 'message', content: [{ text: 'then "task_complete" arrives' }] } }+ expect(await sessionBusy(codex('ended', [event('task_started'), talk, event('task_complete'), talk]))).toBe(false)+ expect(await sessionBusy(codex('aborted', [event('task_started'), event('turn_aborted')]))).toBe(false)+ expect(await sessionBusy(codex('working', [event('task_complete'), event('task_started'), talk]))).toBe(true)+ expect(await sessionBusy(codex('unsaid', []))).toBe(true)+ })+})++describe('stopSessionOwner', () => {+ it('asks it to quit, makes it after five seconds, and gives the terminal its cursor back', async () => {+ const signals: string[] = []+ const written: string[] = []+ let living = true+ let slept = 0+ const opts = {+ alive: () => living,+ kill: (_pid: number, signal: NodeJS.Signals) => { signals.push(signal); if (signal === 'SIGTERM' && slept === 0) return; living = false },+ sleep: async (ms: number) => { slept += ms },+ writeTty: async (tty: string, text: string) => { written.push(`${tty} ${JSON.stringify(text)}`) },+ }+ expect(await stopSessionOwner({ pid: 7, tty: '/dev/ttys009' }, opts)).toBe(true)+ expect(signals).toEqual(['SIGTERM', 'SIGKILL'])+ expect(slept).toBe(5_000)+ expect(written).toEqual(['/dev/ttys009 "\\u001b[?25h"'])++ // One that quits when asked is not made to; one that will not quit at all is reported.+ signals.length = 0; living = true; slept = 1+ expect(await stopSessionOwner({ pid: 7, tty: null }, opts)).toBe(true)+ expect(signals).toEqual(['SIGTERM'])+ expect(await stopSessionOwner({ pid: 8, tty: null }, { ...opts, alive: () => true, kill: () => undefined })).toBe(false)})})diff --git a/cli/src/lib/sessionSearch/external.ts b/cli/src/lib/sessionSearch/external.tsindex 841ea1080..3681f8a1d 100644--- a/cli/src/lib/sessionSearch/external.ts+++ b/cli/src/lib/sessionSearch/external.ts@@ -184,6 +184,19 @@ async function codexTitles(path: string): Promise<Map<string, string>> {return titles}+/** Where an open session is: a terminal, which Harness can take it over from, or an app, which it cannot. */+export type OpenIn = 'terminal' | 'app'++/** The process that has a session open. */+export interface SessionOwner {+ pid: number+ engine: ExternalEngine+ /** The terminal it runs in (`/dev/ttys003`), or null for an app: an app is never stopped from here. */+ tty: string | null+ /** What says whether it is mid-turn: Claude Code's `sessions/<pid>.json`, or Codex's rollout. */+ record: string+}+export interface OpenSessionsOptions {/** `~/.claude`: running Claude Code processes each keep `sessions/<pid>.json` there. */claudeHome: string@@ -191,74 +204,204 @@ export interface OpenSessionsOptions {maxAgeMs?: number/** Whether a process is running; tests replace it. */alive?: (pid: number) => boolean- /** The Codex rollouts open in a running process; tests replace it. */- openRollouts?: () => Promise<string[]>+ /** The Codex rollouts open in a running process, and the process; tests replace it. */+ openRollouts?: () => Promise<Array<{ pid: number; path: string }>>+ /** The terminal each process runs in, or null; tests replace it. */+ ttys?: (pids: number[]) => Promise<Map<number, string | null>>now?: () => number}+type OpenAnswer = { at: number; owners: Map<string, SessionOwner>; open: Map<string, OpenIn> }+/*** Which sessions are open in a running process right now, so Cmd-P does not open one a second time- * beside a terminal that still has it: both would write the same conversation.+ * beside a terminal that still has it: both would write the same conversation. One open in a+ * terminal can be taken over instead (`owner`, `stopSessionOwner`).** Claude Code says so itself — each running process keeps `~/.claude/sessions/<pid>.json` naming its* session. Codex keeps no such record, but holds its rollout file open while it runs, so the- * operating system says which are (`lsof`).+ * operating system says which are (`lsof`). A process with a terminal is one a person runs there;+ * the engines' apps have none.*/export class OpenSessions {- private answer: { at: number; ids: Set<string> } | null = null- private asking: Promise<Set<string>> | null = null+ private answer: OpenAnswer | null = null+ private asking: Promise<OpenAnswer> | null = nullconstructor(private readonly opts: OpenSessionsOptions) {}/** The last answer, however old; empty before the first. Never waits. */- known(): ReadonlySet<string> {+ known(): ReadonlyMap<string, OpenIn> {const now = (this.opts.now ?? Date.now)()if (!this.answer || now - this.answer.at > (this.opts.maxAgeMs ?? 5_000)) void this.fresh()- return this.answer?.ids ?? new Set()+ return this.answer?.open ?? new Map()}/** An answer at most `maxAgeMs` old. */- fresh(): Promise<Set<string>> {+ async fresh(): Promise<ReadonlyMap<string, OpenIn>> {+ return (await this.current()).open+ }++ /** The process that has [sessionId] open, looked at now rather than taken from a recent answer. */+ async owner(sessionId: string): Promise<SessionOwner | null> {+ if (!this.asking) this.answer = null+ return (await this.current()).owners.get(sessionId) ?? null+ }++ private current(): Promise<OpenAnswer> {const now = (this.opts.now ?? Date.now)()- if (this.answer && now - this.answer.at <= (this.opts.maxAgeMs ?? 5_000)) return Promise.resolve(this.answer.ids)- this.asking ??= this.read().then((ids) => {- this.answer = { at: (this.opts.now ?? Date.now)(), ids }- return ids+ if (this.answer && now - this.answer.at <= (this.opts.maxAgeMs ?? 5_000)) return Promise.resolve(this.answer)+ this.asking ??= this.read().then((owners) => {+ const open = new Map([...owners].map(([id, owner]): [string, OpenIn] => [id, owner.tty ? 'terminal' : 'app']))+ this.answer = { at: (this.opts.now ?? Date.now)(), owners, open }+ return this.answer}).finally(() => { this.asking = null })return this.asking}- private async read(): Promise<Set<string>> {- const ids = new Set<string>()+ private async read(): Promise<Map<string, SessionOwner>> {+ const owners = new Map<string, SessionOwner>()const alive = this.opts.alive ?? processAliveconst dir = join(this.opts.claudeHome, 'sessions')for (const file of await entries(dir)) {if (!file.isFile() || !file.name.endsWith('.json')) continue+ const path = join(dir, file.name)try {- const record = JSON.parse(await readFile(join(dir, file.name), 'utf8')) as { pid?: unknown; sessionId?: unknown }- if (typeof record.pid === 'number' && typeof record.sessionId === 'string' && alive(record.pid)) ids.add(record.sessionId)+ const record = JSON.parse(await readFile(path, 'utf8')) as { pid?: unknown; sessionId?: unknown }+ if (typeof record.pid === 'number' && typeof record.sessionId === 'string' && alive(record.pid)) {+ owners.set(record.sessionId, { pid: record.pid, engine: 'claude', tty: null, record: path })+ }} catch { /* one being written, or gone */ }}- for (const path of await (this.opts.openRollouts ?? openCodexRollouts)().catch(() => [])) {+ for (const { pid, path } of await (this.opts.openRollouts ?? openCodexRollouts)().catch(() => [])) {const id = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(path)?.[1]- if (id) ids.add(id)+ if (id) owners.set(id, { pid, engine: 'codex', tty: null, record: path })+ }+ if (owners.size) {+ const ttys = await (this.opts.ttys ?? processTtys)([...new Set([...owners.values()].map((owner) => owner.pid))]).catch(() => new Map<number, string | null>())+ for (const owner of owners.values()) owner.tty = ttys.get(owner.pid) ?? null+ }+ return owners+ }+}++/**+ * Whether [owner] is in the middle of a turn. Claude Code's record says `idle` between turns. A Codex+ * rollout marks a turn's start (`task_started`) and its end (`task_complete`, or `turn_aborted`), so+ * the last of those near its end says. A file that cannot say counts as busy: the answer only+ * decides whether to ask before stopping it.+ */+export async function sessionBusy(owner: Pick<SessionOwner, 'engine' | 'record'>): Promise<boolean> {+ if (owner.engine === 'claude') {+ try {+ return (JSON.parse(await readFile(owner.record, 'utf8')) as { status?: unknown }).status !== 'idle'+ } catch {+ return false // gone: the process ended with it+ }+ }+ for (const bytes of [256 * 1024, 4 * 1024 * 1024]) {+ const lines = (await readTail(owner.record, bytes)).split('\n')+ for (let i = lines.length - 1; i > 0; i--) {+ const line = lines[i]+ if (!line.includes('"event_msg"') || !TURN_MARK.test(line)) continue+ try {+ const kind = (JSON.parse(line) as { payload?: { type?: unknown } }).payload?.type+ if (kind === 'task_started') return true+ if (kind === 'task_complete' || kind === 'turn_aborted') return false+ } catch { /* the line being written */ }}- return ids}+ return true}-function processAlive(pid: number): boolean {+const TURN_MARK = /"(task_started|task_complete|turn_aborted)"/++async function readTail(path: string, bytes: number): Promise<string> {+ const handle = await open(path, 'r').catch(() => null)+ if (!handle) return ''+ try {+ const { size } = await handle.stat()+ const length = Math.min(size, bytes)+ const buffer = Buffer.alloc(length)+ await handle.read(buffer, 0, length, size - length)+ return buffer.toString('utf8')+ } finally {+ await handle.close()+ }+}++export interface StopOptions {+ alive?: (pid: number) => boolean+ kill?: (pid: number, signal: NodeJS.Signals) => void+ sleep?: (ms: number) => Promise<void>+ /** Writes to the owner's terminal; tests replace it. */+ writeTty?: (tty: string, text: string) => Promise<void>+}++/**+ * Stops the terminal process that has a session open, so Harness can resume it: asked to quit+ * (SIGTERM, which both engines answer by saving and restoring the terminal), then made to after five+ * seconds. Codex leaves its cursor hidden when told to quit rather than typing its way out, so the+ * terminal gets it back. Whether the process is gone.+ */+export async function stopSessionOwner(owner: Pick<SessionOwner, 'pid' | 'tty'>, opts: StopOptions = {}): Promise<boolean> {+ const alive = opts.alive ?? processAlive+ const kill = opts.kill ?? ((pid: number, signal: NodeJS.Signals) => { process.kill(pid, signal) })+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))+ const gone = async (ms: number): Promise<boolean> => {+ for (let waited = 0; waited < ms; waited += 100) {+ if (!alive(owner.pid)) return true+ await sleep(100)+ }+ return !alive(owner.pid)+ }+ const signal = (name: NodeJS.Signals): void => {+ try { kill(owner.pid, name) } catch { /* already gone */ }+ }+ signal('SIGTERM')+ if (!await gone(5_000)) {+ signal('SIGKILL')+ if (!await gone(2_000)) return false+ }+ if (owner.tty) await (opts.writeTty ?? writeTty)(owner.tty, '\x1b[?25h').catch(() => undefined)+ return true+}++async function writeTty(tty: string, text: string): Promise<void> {+ const handle = await open(tty, 'w')+ try { await handle.write(text) } finally { await handle.close() }+}++export function processAlive(pid: number): boolean {try { process.kill(pid, 0); return true } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM' }}-/** The rollout files Codex processes have open: `lsof` over processes named codex. */-function openCodexRollouts(): Promise<string[]> {+/** The rollout files Codex processes have open, and which process: `lsof` over processes named codex. */+function openCodexRollouts(): Promise<Array<{ pid: number; path: string }>> {return new Promise((resolve) => {- execFile('lsof', ['-n', '-P', '-Fn', '-c', 'codex', '-c', 'Codex'], { timeout: 3_000, maxBuffer: 8 * 1024 * 1024 }, (_error, stdout) => {+ execFile('lsof', ['-n', '-P', '-Fpn', '-c', 'codex', '-c', 'Codex'], { timeout: 3_000, maxBuffer: 8 * 1024 * 1024 }, (_error, stdout) => {// lsof exits 1 when a name matches no process; what it printed is still the answer.- resolve(String(stdout ?? '').split('\n')- .filter((line) => line.startsWith('n') && line.includes('rollout-') && line.endsWith('.jsonl'))- .map((line) => line.slice(1)))+ const found: Array<{ pid: number; path: string }> = []+ let pid = 0+ for (const line of String(stdout ?? '').split('\n')) {+ if (line.startsWith('p')) pid = Number(line.slice(1)) || 0+ else if (pid && line.startsWith('n') && line.includes('rollout-') && line.endsWith('.jsonl')) found.push({ pid, path: line.slice(1) })+ }+ resolve(found)+ })+ })+}++/** Each process's terminal (`ps -o tty`): `ttys003` on macOS, `pts/3` on Linux, `??` or `?` for none. */+function processTtys(pids: number[]): Promise<Map<number, string | null>> {+ return new Promise((resolve) => {+ execFile('ps', ['-o', 'pid=,tty=', '-p', pids.join(',')], { timeout: 3_000 }, (_error, stdout) => {+ const ttys = new Map<number, string | null>()+ for (const line of String(stdout ?? '').split('\n')) {+ const [pid, tty] = line.trim().split(/\s+/)+ if (!pid) continue+ ttys.set(Number(pid), tty && !tty.startsWith('?') ? `/dev/${tty}` : null)+ }+ resolve(ttys)})})}diff --git a/cli/src/lib/sessionSearch/indexer.spec.ts b/cli/src/lib/sessionSearch/indexer.spec.tsindex 9032a9e28..bd7e01e53 100644--- a/cli/src/lib/sessionSearch/indexer.spec.ts+++ b/cli/src/lib/sessionSearch/indexer.spec.ts@@ -109,7 +109,7 @@ describe('SessionSearchIndex', () => {const untitledFile = join(dir, 'e2.jsonl')writeFileSync(untitledFile, prompt('compare retention\nby cohort please', 0) + answer('Day-7 is 35%.', 1))const store = SessionSearchStore.open(':memory:')!- const open = new Set(['e1'])+ const open = new Map([['e1', 'terminal' as const]])let sources: SearchSource[] = [{ agentId: '', sessionId: 'e1', engine: 'claude', transcriptPath: claudeFile, header: '', updatedAt: 2, external: { cwd: '/work/dial', origin: 'terminal', title: '' } },{ agentId: '', sessionId: 'e2', engine: 'claude', transcriptPath: untitledFile, header: '', updatedAt: 1, external: { cwd: '/work/cohorts', origin: 'claude-app', title: '' } },@@ -129,10 +129,10 @@ describe('SessionSearchIndex', () => {expect(store.session('e2')?.title).toBe('compare retention by cohort please')// Found by its title, marked as not Harness's, and as open elsewhere.const hit = index.search('dial fix').hits[0]- expect(hit).toMatchObject({ sessionId: 'e1', agentId: '', external: { title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true } })+ expect(hit).toMatchObject({ sessionId: 'e1', agentId: '', external: { title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true, openIn: 'terminal' } })expect(index.search('cohort').hits[0]).toMatchObject({ sessionId: 'e2', external: { origin: 'claude-app', open: false } })const tail = await index.tail('e1')- expect(tail?.external).toEqual({ title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true })+ expect(tail?.external).toEqual({ title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true, openIn: 'terminal' })// Its file gone, it leaves the index at the next sweep.sources = sources.filter((source) => source.sessionId !== 'e2')diff --git a/cli/src/lib/sessionSearch/indexer.ts b/cli/src/lib/sessionSearch/indexer.tsindex f015028a5..eb6d90791 100644--- a/cli/src/lib/sessionSearch/indexer.ts+++ b/cli/src/lib/sessionSearch/indexer.ts@@ -103,7 +103,7 @@ export interface SessionSearchIndexOptions {* Which sessions are open in a running process right now (external.ts `OpenSessions`), so a* conversation Harness did not start says whether a terminal still has it. `known` never waits.*/- openSessions?: { known(): ReadonlySet<string>; fresh(): Promise<ReadonlySet<string>> }+ openSessions?: { known(): ReadonlyMap<string, 'terminal' | 'app'>; fresh(): Promise<ReadonlyMap<string, 'terminal' | 'app'>> }/** Looks again for conversations Harness did not start, before each sweep lists its sources. */discover?: () => Promise<unknown>/** Between full sweeps. */@@ -212,7 +212,12 @@ export class SessionSearchIndex {// Whether a terminal still has it, as last looked: a search never waits for a process table.if (hits.some((hit) => hit.external) && this.opts.openSessions) {const open = this.opts.openSessions.known()- for (const hit of hits) if (hit.external) hit.external.open = open.has(hit.sessionId)+ for (const hit of hits) {+ if (!hit.external) continue+ hit.external.open = open.has(hit.sessionId)+ const where = open.get(hit.sessionId)+ if (where) hit.external.openIn = where+ }}const indexed = this.opts.store.counts().sessionsreturn { hits, indexed, pending: this.queue.size, tookMs: Math.round((performance.now() - started) * 10) / 10 }@@ -245,7 +250,8 @@ export class SessionSearchIndex {if (tail && session && !session.agentId) {// A preview of a conversation Harness did not start says whether a terminal has it, as of now.const open = await this.opts.openSessions?.fresh().catch(() => null)- tail.external = { title: session.title ?? '', cwd: session.cwd ?? '', origin: session.origin ?? '', open: open?.has(sessionId) ?? false }+ const where = open?.get(sessionId)+ tail.external = { title: session.title ?? '', cwd: session.cwd ?? '', origin: session.origin ?? '', open: open?.has(sessionId) ?? false, ...(where ? { openIn: where } : {}) }}return tail}diff --git a/cli/src/lib/sessionSearch/store.ts b/cli/src/lib/sessionSearch/store.tsindex afefeac7a..08ee51495 100644--- a/cli/src/lib/sessionSearch/store.ts+++ b/cli/src/lib/sessionSearch/store.ts@@ -65,6 +65,8 @@ export interface ExternalHit {origin: string/** Open in a running process elsewhere (a terminal, the engine's app): not to be opened twice. */open?: boolean+ /** Where it is open: a terminal, which Harness can take it over from, or an app, which it cannot. */+ openIn?: 'terminal' | 'app'}export interface SearchHit {diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 8422f66aa..7bd496b8f 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -70,6 +70,7 @@ import '../state/toolbar_notices.dart';import '../widgets/machine_actions.dart';import '../widgets/rename_agent_dialog.dart';import '../widgets/delete_agent_dialog.dart';+import '../widgets/take_over_dialog.dart';import '../widgets/fork_agent_dialog.dart';import '../widgets/restart_agent_action.dart';import '../widgets/new_agent_dialog.dart';@@ -2487,6 +2488,7 @@ class _SwarmScreenState extends State<SwarmScreen> {String target, {PaneSplitRequest? split,HarnessPlacement? placement,+ TakeOver? takeOver,}) async {final command = selected.destination.commandId;if (command != null) {@@ -2519,8 +2521,40 @@ class _SwarmScreenState extends State<SwarmScreen> {projects: _projects.projects,split: split,placement: placement,+ takeOver: takeOver,);} on SwarmResumeFailure catch (failure) {+ // Open in a terminal: ask whether to move it here — and, mid-turn,+ // whether to wait for the turn or stop it. Asked again when a turn+ // started between the question and the answer.+ final ask =+ failure.canTakeOver &&+ (takeOver == null || (takeOver == TakeOver.idle && failure.busy));+ if (ask && failure.destination.external != null) {+ TakeOver? choice;+ await _dialog(() async {+ choice = await askTakeOver(+ context,+ title: failure.destination.title,+ engine: failure.destination.external!.engine,+ busy: failure.busy,+ machine: failure.destination.machineLabel.isEmpty+ ? null+ : failure.destination.machineLabel,+ keymap: _keymap,+ );+ });+ if (choice case final choice? when mounted) {+ await _activateSearch(+ selected,+ target,+ split: split,+ placement: placement,+ takeOver: choice,+ );+ }+ return;+ }_showResumeFailure(failure, target: target, placement: placement);return;}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex c145ff5ea..726826e36 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -47,6 +47,7 @@ import '../terminal/terminal_theme_store.dart';import '../logging/app_log.dart';import '../shared/theme/app_theme.dart' as grid;import '../terminal/remote_media_download.dart';+import 'take_over.dart';import '../widgets/engine_identity.dart'show allEngines, engineIdentity, isTerminalEngine;import '../store/store_screen.dart' show openStoreAgent;@@ -214,6 +215,11 @@ class AgentCreationAttempt {bool get awaitingConfirmation => _awaitingConfirmation;+ /// The machine's code for a request it refused before launching anything,+ /// such as `SESSION_BUSY_IN_TERMINAL`: what a caller can offer next.+ String? _refusal;+ String? get refusal => _refusal;+/// A completed folder survives a refused agent launch, so correcting the/// agent choice does not clone or create the same project again.String? get preparedFolder => _preparedFolder;@@ -7342,7 +7348,10 @@ class AppNotifier extends ChangeNotifier {/// The machine refuses one open elsewhere, already a harness, or whose folder/// is gone, and says why. Null when it started; otherwise what to tell the/// person.- Future<String?> resumeConversation(+ /// Opens a conversation Harness did not start as a new harness. One open in+ /// a terminal is refused unless [takeOver] says how to take it over from+ /// there; the refusal's code says whether that terminal is mid-turn.+ Future<({String? error, String? refusal})> resumeConversation(String machineId, {required String engine,required String folder,@@ -7350,18 +7359,25 @@ class AppNotifier extends ChangeNotifier {String? name,String? swarmId,HarnessPlacement? placement,- }) => _create(- machineId,- {- 'engine': engine,- 'cwd': folder,- 'bypassPermission': true,- 'name': ?name,- 'resumeSessionId': sessionId,- },- swarmId: swarmId,- placement: placement,- );+ TakeOver? takeOver,+ }) async {+ final attempt = AgentCreationAttempt();+ final error = await _create(+ machineId,+ {+ 'engine': engine,+ 'cwd': folder,+ 'bypassPermission': true,+ 'name': ?name,+ 'resumeSessionId': sessionId,+ 'takeOver': ?takeOver?.name,+ },+ swarmId: swarmId,+ placement: placement,+ attempt: attempt,+ );+ return (error: error, refusal: error == null ? null : attempt.refusal);+ }Future<String?> _create(String machineId,@@ -7492,6 +7508,9 @@ class AppNotifier extends ChangeNotifier {'SESSION_IN_HARNESS' ||'SESSION_NOT_FOUND' ||'SESSION_FOLDER_GONE' ||+ 'SESSION_OPEN_IN_TERMINAL' ||+ 'SESSION_BUSY_IN_TERMINAL' ||+ 'SESSION_STOP_FAILED' ||'INVALID_SESSION' =>detail ?? 'Could not open that conversation on $machine.',// A daemon that predates the terminal engine refuses it by name; the@@ -7702,9 +7721,13 @@ class AppNotifier extends ChangeNotifier {'SESSION_IN_HARNESS','SESSION_NOT_FOUND','SESSION_FOLDER_GONE',+ 'SESSION_OPEN_IN_TERMINAL',+ 'SESSION_BUSY_IN_TERMINAL',+ 'SESSION_STOP_FAILED','INVALID_SESSION',};if (refusedBeforeLaunch.contains(failure.code)) {+ creation._refusal = failure.code;if (failure.code == 'INVALID_CWD' && choices['projectSource'] != null) {return creation._complete('Update Harness CLI on $machineName to create or clone project folders. Local can open an existing folder.',@@ -7753,6 +7776,7 @@ class AppNotifier extends ChangeNotifier {when folder.isNotEmpty) {creation._preparedFolder = folder;}+ creation._refusal = failure['code'] as String;return creation._complete(_creationFailureMessage(failure['code'] as String,diff --git a/desktop/lib/state/session_content_search.dart b/desktop/lib/state/session_content_search.dartindex 7f5898dec..0f60c501a 100644--- a/desktop/lib/state/session_content_search.dart+++ b/desktop/lib/state/session_content_search.dart@@ -103,7 +103,9 @@ class SessionContentHit {position: position,turn: turn is int ? turn : 0,at: at is int ? DateTime.fromMillisecondsSinceEpoch(at) : null,- lastAt: lastAt is int ? DateTime.fromMillisecondsSinceEpoch(lastAt) : null,+ lastAt: lastAt is int+ ? DateTime.fromMillisecondsSinceEpoch(lastAt)+ : null,external: agentId.isEmpty ? external : null,);}@@ -127,6 +129,10 @@ class SessionContentHit {origin: origin is String ? origin : 'terminal',title: title is String ? title : '',open: external['open'] == true,+ openIn: switch (external['openIn']) {+ final String where when where == 'terminal' || where == 'app' => where,+ _ => null,+ },);}diff --git a/desktop/lib/state/session_tail.dart b/desktop/lib/state/session_tail.dartindex b6cf5a2b5..bcf23e246 100644--- a/desktop/lib/state/session_tail.dart+++ b/desktop/lib/state/session_tail.dart@@ -53,6 +53,7 @@ class SessionTail {required this.fetchedAt,this.lastAsk,this.openElsewhere = false,+ this.openIn,});final List<SessionTailRow> rows;@@ -68,6 +69,9 @@ class SessionTail {/// elsewhere, as its machine found when it answered.final bool openElsewhere;+ /// Where: `terminal`, which Harness can take it over from, or `app`.+ final String? openIn;+static SessionTail? fromReply(Map<String, dynamic> reply, DateTime now) {final rows = reply['rows'];if (rows is! List) return null;@@ -80,6 +84,12 @@ class SessionTail {openElsewhere:reply['external'] is Map &&(reply['external'] as Map)['open'] == true,+ openIn: switch (reply['external']) {+ {'openIn': final String where}+ when where == 'terminal' || where == 'app' =>+ where,+ _ => null,+ },);}}@@ -182,6 +192,7 @@ class SessionTails extends ChangeNotifier {fetchedAt: page.fetchedAt,lastAsk: page.lastAsk,openElsewhere: page.openElsewhere,+ openIn: page.openIn,),);}@@ -217,6 +228,7 @@ class SessionTails extends ChangeNotifier {fetchedAt: current.fetchedAt,lastAsk: current.lastAsk,openElsewhere: current.openElsewhere,+ openIn: current.openIn,),);} finally {diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dartindex 26fecbb05..115723bc4 100644--- a/desktop/lib/state/swarm_navigation.dart+++ b/desktop/lib/state/swarm_navigation.dart@@ -17,6 +17,7 @@ import 'session_content_search.dart';import 'session_preview.dart';import 'swarm.dart';import 'swarm_catalog.dart';+import 'take_over.dart';import 'terminal_pane.dart';String swarmDestinationId(String id) => 'swarm:$id';@@ -252,6 +253,7 @@ class ExternalSessionRef {required this.origin,this.title = '',this.open = false,+ this.openIn,});final String sessionId, engine, cwd, title;@@ -263,6 +265,14 @@ class ExternalSessionRef {/// processes writing one conversation.final bool open;+ /// Where it is open: `terminal`, which Harness can take it over from, or+ /// `app`, which it cannot. Null when it is not open, or the machine predates+ /// taking over.+ final String? openIn;++ /// Open, and only in a terminal: opening it here moves it, once asked.+ bool get inTerminal => open && openIn == 'terminal';+/// Where it ran, as a person says it.String get originLabel => switch (origin) {'claude-app' => 'Claude app',@@ -388,9 +398,19 @@ class SwarmDestination {enum SwarmSearchAction { open, addHere }class SwarmResumeFailure implements Exception {- const SwarmResumeFailure(this.destination, this.message);+ const SwarmResumeFailure(this.destination, this.message, {this.code});final SwarmDestination destination;final String message;++ /// The machine's refusal, such as `SESSION_BUSY_IN_TERMINAL`, when it said.+ final String? code;++ /// A conversation open in a terminal, which can be taken over from there.+ bool get canTakeOver =>+ code == 'SESSION_OPEN_IN_TERMINAL' || code == 'SESSION_BUSY_IN_TERMINAL';++ /// Mid-turn in that terminal: wait for the turn, or stop it.+ bool get busy => code == 'SESSION_BUSY_IN_TERMINAL';}Future<void> _resumeStoppedDestination(@@ -837,14 +857,16 @@ Future<bool> activateSwarmSearchSelection(List<SavedSwarmProject> projects = const [],PaneSplitRequest? split,HarnessPlacement? placement,+ TakeOver? takeOver,}) async {final destination = selection.destination;if (destination.external case final external?) {final machineId = destination.machineId;if (machineId == null || split != null) return false;// A new harness that resumes it, in its own folder: the machine refuses one- // that is open elsewhere, or already a harness, and says so.- final error = await app.resumeConversation(+ // that is open elsewhere, or already a harness, and says so — and one open+ // in a terminal until asked how to take it over from there.+ final (:error, :refusal) = await app.resumeConversation(machineId,engine: external.engine,folder: external.cwd,@@ -852,8 +874,11 @@ Future<bool> activateSwarmSearchSelection(name: external.title.isEmpty ? null : external.title,swarmId: destinationSwarmId,placement: placement ?? HarnessPlacement.currentTab,+ takeOver: takeOver,);- if (error != null) throw SwarmResumeFailure(destination, error);+ if (error != null) {+ throw SwarmResumeFailure(destination, error, code: refusal);+ }return true;}if (placement != null) {diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex dd0a9b2f8..541898482 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -1539,7 +1539,10 @@ class SwarmSearchController extends ChangeNotifier {sessionId: external.sessionId,));if (external.open || previewed?.openElsewhere == true) {- return external.origin == 'terminal'+ // One in a terminal can be moved here: opening it asks how.+ final where = previewed?.openIn ?? external.openIn;+ if (where == 'terminal') return null;+ return external.origin == 'terminal' && where == null? 'Open in another terminal': 'Open in the ${external.originLabel}';}diff --git a/desktop/lib/state/take_over.dart b/desktop/lib/state/take_over.dartnew file mode 100644index 000000000..f6aab54d5--- /dev/null+++ b/desktop/lib/state/take_over.dart@@ -0,0 +1,12 @@+/// How to take a conversation over from the terminal that has it open: the+/// `takeOver` of `agent_create`.+enum TakeOver {+ /// It is between turns: its terminal quits and it opens here.+ idle,++ /// Mid-turn: the turn is stopped, and the conversation told to continue.+ now,++ /// Mid-turn: it moves here when the turn ends.+ wait,+}diff --git a/desktop/lib/state/welcome_sessions.dart b/desktop/lib/state/welcome_sessions.dartindex dc1b8873e..79fabc037 100644--- a/desktop/lib/state/welcome_sessions.dart+++ b/desktop/lib/state/welcome_sessions.dart@@ -83,8 +83,9 @@ class WelcomeSessions extends ChangeNotifier {final external = <SwarmDestination>[for (final hits in answers)for (final hit in hits ?? const <SessionContentHit>[])- // One a terminal still has is not offered: it cannot be opened here.- if (hit.external case final ref? when !ref.open)+ // One an app still has is not offered: it cannot be opened here.+ // One a terminal has can be: opening it asks to move it.+ if (hit.external case final ref? when !ref.open || ref.inTerminal)externalSessionDestination(hit,ref,diff --git a/desktop/lib/widgets/swarm_search_preview.dart b/desktop/lib/widgets/swarm_search_preview.dartindex 678eecfc2..718674194 100644--- a/desktop/lib/widgets/swarm_search_preview.dart+++ b/desktop/lib/widgets/swarm_search_preview.dart@@ -223,11 +223,10 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {if (open)Padding(padding: EdgeInsets.only(top: gap * .5),- child: Text(- '${widget.search.sessionUnavailable(row) ?? 'Open elsewhere'}. '- 'Close it there to open it here.',- style: muted.copyWith(color: warning),- ),+ child: Text(switch (widget.search.sessionUnavailable(row)) {+ null => 'Open in a terminal. Opening it here moves it.',+ final where => '$where. Close it there to open it here.',+ }, style: muted.copyWith(color: warning)),),],);diff --git a/desktop/lib/widgets/take_over_dialog.dart b/desktop/lib/widgets/take_over_dialog.dartnew file mode 100644index 000000000..d417bba19--- /dev/null+++ b/desktop/lib/widgets/take_over_dialog.dart@@ -0,0 +1,176 @@+import 'package:flutter/material.dart';++import '../shortcuts/app_keymap.dart';+import '../state/take_over.dart';+import '../terminal/terminal_text.dart';+import 'box_chrome.dart';+import 'terminal_prompt.dart';++export '../state/take_over.dart';++/// Asks whether to move a conversation open in a terminal into Harness. Idle,+/// the choice is to move it. Mid-turn, the choice is to wait for the turn to+/// end or stop it now. Null when dismissed: it stays where it is.+Future<TakeOver?> askTakeOver(+ BuildContext context, {+ required String title,+ required String engine,+ required bool busy,+ String? machine,+ AppKeymap? keymap,+}) => showTerminalPrompt<TakeOver>(+ context,+ keymap: keymap,+ builder: (_) => _TakeOverPrompt(+ title: title,+ engine: engine,+ busy: busy,+ machine: machine,+ ),+);++class _TakeOverPrompt extends StatefulWidget {+ const _TakeOverPrompt({+ required this.title,+ required this.engine,+ required this.busy,+ this.machine,+ });+ final String title, engine;+ final bool busy;+ final String? machine;+ @override+ State<_TakeOverPrompt> createState() => _TakeOverPromptState();+}++class _TakeOverPromptState extends State<_TakeOverPrompt> {+ final _first = FocusNode(debugLabel: 'Take over');++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _first.requestFocus();+ });+ }++ @override+ void dispose() {+ _first.dispose();+ super.dispose();+ }++ void _pick(TakeOver? choice) => Navigator.pop(context, choice);++ String get _engineName => switch (widget.engine) {+ 'claude' => 'Claude Code',+ 'codex' => 'Codex',+ final other => other,+ };++ @override+ Widget build(BuildContext context) {+ TerminalFontScope.watch(context);+ final busy = widget.busy;+ return ListenableBuilder(+ listenable: terminalFontStore,+ builder: (context, _) => TerminalPromptKeys(+ cancel: () => _pick(null),+ child: TerminalPrompt(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ 'Move to Harness',+ style: boxMonoStyle(color: kBoxFaint),+ ),+ const SizedBox(height: 12),+ Text(+ widget.title,+ key: const ValueKey('take-over-title'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: boxMonoStyle(weight: FontWeight.w600),+ ),+ if (widget.machine case final machine?) ...[+ const SizedBox(height: 4),+ Text(machine, style: boxMonoStyle(color: kBoxFaint)),+ ],+ const SizedBox(height: 10),+ Text(+ busy+ ? '$_engineName is working on it in a terminal.'+ : 'It is open in $_engineName in a terminal. '+ 'Moving it here quits it there.',+ style: boxMonoStyle(color: Colors.white70),+ ),+ const SizedBox(height: 8),+ Text(+ busy+ ? 'Wait moves it here when this turn ends. '+ 'Take Over Now stops the turn and tells it to continue.'+ : 'The conversation is kept.',+ style: boxMonoStyle(color: kBoxFaint),+ ),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(14, 0, 14, 10),+ child: Wrap(+ spacing: 12,+ children: [+ if (busy) ...[+ terminalPromptButton(+ 'Wait',+ () => _pick(TakeOver.wait),+ focusNode: _first,+ key: const Key('take-over-wait'),+ ),+ terminalPromptButton(+ 'Take Over Now',+ () => _pick(TakeOver.now),+ danger: true,+ key: const Key('take-over-now'),+ ),+ ] else+ terminalPromptButton(+ 'Move Here',+ () => _pick(TakeOver.idle),+ focusNode: _first,+ key: const Key('take-over-move'),+ ),+ terminalPromptButton('Cancel', () => _pick(null)),+ ],+ ),+ ),+ BoxHintStrip(+ hints: [+ BoxHint(+ terminalPromptHint(context, 'picker.accept', 'enter'),+ 'select',+ ),+ BoxHint(+ terminalPromptHint(context, 'picker.complete', 'tab'),+ 'controls',+ ),+ BoxHint(+ terminalPromptHint(context, 'picker.cancel', 'esc'),+ 'close',+ onTap: () => _pick(null),+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ );+ }+}diff --git a/desktop/test/session_search_rendering_test.dart b/desktop/test/session_search_rendering_test.dartindex c7ca10b66..fa8045e42 100644--- a/desktop/test/session_search_rendering_test.dart+++ b/desktop/test/session_search_rendering_test.dart@@ -307,7 +307,12 @@ void main() {(tester) async {const session = '01a0c4ad-de5e-7000-8000-000000000001';const busy = '01a0c4ad-de5e-7000-8000-000000000002';- Map<String, dynamic> external(String id, {required bool open}) => {+ const movable = '01a0c4ad-de5e-7000-8000-000000000003';+ Map<String, dynamic> external(+ String id, {+ required bool open,+ String? openIn,+ }) => {'agentId': '','sessionId': id,'engine': 'codex',@@ -324,6 +329,7 @@ void main() {'cwd': '/work/cohorts','origin': open ? 'terminal' : 'codex-app','open': open,+ 'openIn': ?openIn,},};final connection = TailConnection(@@ -331,6 +337,7 @@ void main() {'retention cohorts': [external(session, open: false),external(busy, open: true),+ external(movable, open: true, openIn: 'terminal'),],},tail: (payload) => {@@ -410,6 +417,12 @@ void main() {search.sessionUnavailable(open),contains('Open in another terminal'),);+ // A machine that can take one over from its terminal says so: it opens.+ final inTerminal = search.rows.firstWhere(+ (row) => row.external?.sessionId == movable,+ );+ expect(search.sessionUnavailable(inTerminal), isNull);+ expect(search.canSubmit(inTerminal), isTrue);// Previewed like any session: what it is, where it ran, its latest turn.while (search.selected?.id != row.id) {diff --git a/desktop/test/welcome_sessions_test.dart b/desktop/test/welcome_sessions_test.dartindex a602f363e..c409c811a 100644--- a/desktop/test/welcome_sessions_test.dart+++ b/desktop/test/welcome_sessions_test.dart@@ -9,6 +9,7 @@ import 'package:harness/widgets/workspace_welcome.dart';import 'keymap_host_test.dart' show key;import 'session_content_search_test.dart' show SearchConnection;+import 'session_search_rendering_test.dart' show TailConnection;import 'swarm_screen_test.dart' show mount;import 'swarm_state_test.dart' show createApp;@@ -19,6 +20,7 @@ Map<String, dynamic> _external(String title,Duration ago, {bool open = false,+ String? openIn,}) => {'agentId': '','sessionId': id,@@ -33,6 +35,7 @@ Map<String, dynamic> _external('cwd': '/work/$id','origin': 'codex-app','open': open,+ 'openIn': ?openIn,},};@@ -206,6 +209,89 @@ void main() {},);+ testWidgets(+ 'one open in a terminal is offered, and opening it asks how to move it here',+ (tester) async {+ newHarnessOpensInBox = true;+ addTearDown(() => newHarnessOpensInBox = false);+ final connection = TailConnection(+ {+ '': [+ _external(+ 'e-busy',+ 'Investigate Harness crash',+ const Duration(minutes: 1),+ open: true,+ openIn: 'terminal',+ ),+ _external(+ 'e-app',+ 'In the Codex app',+ const Duration(minutes: 2),+ open: true,+ openIn: 'app',+ ),+ ],+ },+ tail: (_) => {'rows': [], 'hasMore': false, 'total': 0},+ create: (payload) => payload['takeOver'] == null+ ? {+ 'creationId': payload['creationId'],+ 'state': 'failed',+ 'failure': {+ 'code': 'SESSION_BUSY_IN_TERMINAL',+ 'detail': 'Codex is working on it in a terminal.',+ },+ }+ : {+ 'creationId': payload['creationId'],+ 'state': 'created',+ 'agent': {+ 'id': 'moved',+ 'name': 'Investigate Harness crash',+ 'engine': 'codex',+ },+ },+ );+ final app = createApp(+ connected: true,+ connectionForTest: (_) => connection,+ );+ addTearDown(app.dispose);+ await mount(tester, app);+ await tester.pump(const Duration(milliseconds: 50));+ expect(find.text('Investigate Harness crash'), findsOneWidget);+ expect(find.text('In the Codex app'), findsNothing);++ await key(tester, LogicalKeyboardKey.digit1);+ await tester.pump(const Duration(milliseconds: 100));+ await tester.pump(const Duration(milliseconds: 100));+ expect(+ connection.creates.single,+ containsPair('resumeSessionId', 'e-busy'),+ );+ expect(connection.creates.single.containsKey('takeOver'), isFalse);+ expect(+ find.text('Codex is working on it in a terminal.'),+ findsOneWidget,+ );+ expect(find.byKey(const Key('take-over-wait')), findsOneWidget);++ await tester.tap(find.byKey(const Key('take-over-now')));+ await tester.pump(const Duration(milliseconds: 100));+ await tester.pump(const Duration(milliseconds: 100));+ expect(connection.creates, hasLength(2));+ expect(connection.creates.last, containsPair('takeOver', 'now'));+ expect(+ connection.creates.last,+ containsPair('resumeSessionId', 'e-busy'),+ );+ expect(find.byKey(const Key('take-over-now')), findsNothing);+ expect(app.panes.map((pane) => pane.agentId), ['moved']);+ await tester.pumpWidget(const SizedBox());+ },+ );+testWidgets('without an app it is the welcome it was: no list, no keys taken',(tester) async {diff --git a/docs/research/2026-09-26-session-search.md b/docs/research/2026-09-26-session-search.mdindex 9a5aaae2c..394a08df0 100644--- a/docs/research/2026-09-26-session-search.md+++ b/docs/research/2026-09-26-session-search.md@@ -296,12 +296,31 @@ Enter opens one as a harness resuming it (`lib/sessionSearch/external.ts`).about 210 of 1,227 files, plus a session any Harness agent already has is skipped.- **Shown only when a search matches one**, marked `not in Harness`, and previewed like any session.- **Open elsewhere** is known exactly. A running Claude Code keeps `~/.claude/sessions/<pid>.json`- naming its session, and a running Codex holds its rollout open (`lsof`). ⌘P will not open one- that is still open, and the daemon checks again before it resumes.+ naming its session, and a running Codex holds its rollout open (`lsof`). The process's terminal+ (`ps -o tty`) tells a terminal from an app: the engines' apps have none. One open in an app+ cannot be opened here and is not offered on the welcome page.+- **Taking one over from a terminal.** Most people's sessions are open in a terminal before they+ meet Harness, so those can be moved. Opening one asks first:+ - **Idle** (between turns): *Move Here* stops the terminal's process and resumes the session in+ Harness. Nothing is lost: every finished turn is already on disk.+ - **Mid-turn**: *Wait* opens the harness pane at once. The pane says it is waiting, the daemon+ stops the terminal's process when the turn ends, and the pane then resumes it. Ctrl-C in the+ pane, or closing it, leaves the session where it was. *Take Over Now* stops the turn and+ resumes with a first message of `continue`.+ - **Mid-turn is read the same way:** Claude Code's record says `idle` between turns. A Codex+ rollout's last `task_started`, `task_complete` or `turn_aborted` event says where its turn+ stands.+ - **Stopping** is SIGTERM, then SIGKILL after five seconds. Tested on the real TUIs: both quit+ cleanly and restore the terminal, except that Codex leaves its cursor hidden, so the daemon+ writes the show-cursor sequence to that terminal.+ - The daemon stops the process last, once nothing else can refuse the launch. It never stops an+ app's.- **Resuming** is `agent_create` with `resumeSessionId`: a new pane runs `claude --resume <id>` or`codex resume <id>` in the session's own folder, named after its title. It is refused if the- session is open elsewhere, is already a harness, or its folder is gone (Codex app threads live in- folders people tidy away).+ session is already a harness, or its folder is gone (Codex app threads live in folders people+ tidy away). An open one is refused with `SESSION_OPEN_IN_TERMINAL` or+ `SESSION_BUSY_IN_TERMINAL` until `takeOver` (`idle`, `now` or `wait`) says how to take it over,+ or with `SESSION_OPEN_ELSEWHERE` when an app has it.- ChatGPT conversations and Codex cloud tasks are not on disk, so they cannot be found.- **The welcome page lists them too.** An empty tab shows up to nine rows beside its shortcuts,numbered like the terminal client's home: the harnesses you were just with and these@@ -315,6 +334,16 @@ terminal sessions were found by what was said in them. A session open in a termiStand-in engines confirmed the resume launch (`codex resume <id>`, `claude --resume <id>`, each inits session's folder); no real conversation was touched.+Take-over was checked the same way against made-up sessions, held by stand-in processes in their+own terminals:+- Opened without a choice, a busy Codex session was refused as busy and an idle Claude one as+ open, and both processes were left alone.+- *Move Here* stopped the Claude one and resumed it.+- *Wait* opened a pane saying it was waiting. When `task_complete` was appended to the rollout,+ the daemon stopped the Codex process within two seconds and the pane resumed it.+- *Take Over Now* resumed with `continue`.+- Each terminal got its cursor back.+## Protocol`session_search { query, limit, from?, to? }` → `{ hits: [{ agentId, sessionId, engine, turn, at,