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
Review fixes: a retried Enter never approves a prompt, wrapped prompts are held, a full disk spares the master, offline hooks keep a harness (#831)
Dee3dd59b7aad87
diff --git a/cli/e2e/robustness.e2e.ts b/cli/e2e/robustness.e2e.tsindex dd2533711..04cd97c7f 100644--- a/cli/e2e/robustness.e2e.ts+++ b/cli/e2e/robustness.e2e.ts@@ -4,7 +4,7 @@* outside, a restart in the middle of a turn, and state files that are garbage when it starts. After* each, the same core is serving and a well-behaved client still works.*/-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import WebSocket from 'ws'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'@@ -230,8 +230,13 @@ describe('what the daemon survives', () => {writeFileSync(join(d.dataDir, 'autonomous-device-connections.json'), '{"not": "a list"}', { mode: 0o600 })writeFileSync(join(d.dataDir, 'device-results.json'), '{"version": 1, "entries": [', { mode: 0o600 })await d.start()- await until('the device pieces to be left out', () => /the Wi-Fi device service could not be started/.test(d.log())- && /the Wi-Fi device link could not be started/.test(d.log()), 30_000)+ await until('the device service to be left out', () => /the Wi-Fi device service could not be started/.test(d.log()), 30_000)+ // The requests that need no device piece still answer; the ones that need one say it is not running,+ // not that it is still starting.+ const credential = readFileSync(join(d.dataDir, 'hook-credential'), 'utf8').trim()+ const device = (path: string) => fetch(`http://127.0.0.1:${d.port}/api/autonomous-device/${path}`, { headers: { authorization: `Bearer ${credential}` } })+ await until('the device requests to answer', async () => (await device('list')).status === 200, 30_000, 250)+ expect(await (await device('discover')).json()).toMatchObject({ error: { code: 'UNAVAILABLE', message: expect.stringContaining('is not running on this computer') } })const client = await LocalClient.connect(d)expect(Array.isArray((await client.request('agents_list', { includeStopped: true })).agents)).toBe(true)const agent = await boundAgent(d, client, 'after-the-corruption')diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex e736e9555..c97340bf1 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -1278,6 +1278,15 @@ async function fallbackRegister(input, engine, tmuxPane) {// When an app last opened this agent (RegisteredSession.lastOpenedAt): a fact about the person,// not the process, and the daemon's own rebuild carries it the same way....(Number.isSafeInteger(existing?.lastOpenedAt) && existing.lastOpenedAt > 0 ? { lastOpenedAt: existing.lastOpenedAt } : {}),+ // …and the rest of what `register()` carries: the harness (DSH) and its runtime, the agent file,+ // the permission mode, the subscription model, the default name, the web search a grid launch+ // decided, and a close planned for after the task (#812). Dropped here, a hook in the seconds an+ // update leaves the daemon down relaunched a harness as a plain engine and never closed an agent+ // its person had asked to close. As there, a resume-only row's launch is over once a hook comes.+ ...Object.fromEntries(['gridWebSearch', 'subscriptionModel', 'defaultName', 'dsh', 'dshRuntime', 'agent', 'permissionMode', 'closePlan']+ .filter((key) => existing?.[key] !== undefined && existing?.[key] !== null).map((key) => [key, existing[key]])),+ ...(existing?.resumeOnly === true ? { resumeOnly: true, launch: { state: 'ready' } } : {}),+ ...(existing?.terminalHost === true ? { terminalHost: true } : {}),}const entry = {schemaVersion: 2,diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 589fa8db4..3b248ee0f 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1634,7 +1634,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {const startedAt = Date.now()// Set when the restore pass could not run. The reconciler reads it at call time (its deps are built// long before this is decided) and keeps rows it would otherwise retire — see `onRemoved`.- let restoreDegraded = false+ // Restore did not run this boot (every row), or could not look at these rows (core/agents/discovery.ts).+ let restoreFailed = false+ const restoreUnsurveyed = new Set<string>()let discoveryReady = falselet discoveryError: string | null = null// How a boot that failed AFTER this server bound turns its own status not-ready: the app reads@@ -1964,6 +1966,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {let autonomousDeviceDirect: AutonomousDeviceDirect | undefinedlet deviceStoreRef: ReturnType<typeof createDeviceStore> | undefinedlet autonomousDeviceService: AutonomousDeviceService | undefined+ let devicePartsBuilt = falselet appFormWindow: { machineId: string; connId: string } | undefinedlet appVoiceFocus: { machineId: string; agentId: string; connId: string } | undefinedlet backendRef: BackendSocket | undefined@@ -2509,7 +2512,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {stopHeartbeat,retainExitedSession,stoppedAgents,- restoreDegraded: () => restoreDegraded,+ restoreDegraded: (agentId) => restoreFailed || restoreUnsurveyed.has(agentId),})// HARNESSD_TEST_SLOW_PROBE_MS holds each discovery probe for up to that long, at random, before it is// applied: some scans land at once and some straddle an agent's start, as on a loaded machine. The@@ -2715,7 +2718,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {const { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {onCommandBar: commandBarService,onAutonomousDeviceRequest: async (method, target, body) => {- if (!autonomousDeviceService) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }+ // Until the pieces below are built; after, a piece that could not be is refused by the requests+ // that need it, and the rest (list, status, revoke) answer from the pairings.+ if (!devicePartsBuilt) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }return autonomousDeviceLocalRequest({discover: async () => ({ devices: await runningDevicePart(autonomousDeviceDirect, 'Wi-Fi device link').discover() }),pairStart: ({ code, device }) => runningDevicePart(autonomousDeviceDirect, 'Wi-Fi device link').pair(device, code),@@ -2731,7 +2736,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (!result.ok) throw Object.assign(new Error(result.error), { code: result.error })return { revoked: 1 }},- receipt: target => ({ receipt: autonomousDeviceService!.receipt(target.deviceId, target.idempotencyKey) }),+ receipt: target => ({ receipt: runningDevicePart(autonomousDeviceService, 'Wi-Fi device service').receipt(target.deviceId, target.idempotencyKey) }),}, method, target, body)},resolveHookAgent: engineHooks.resolveHookAgent,@@ -3424,17 +3429,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {clearRemainOnExit: (runtime) => clearPaneRemainOnExit(runtime.paneId),holdRoute: (key, ms) => agentReconciler.holdRoute(key, ms),releaseRoute: (key) => agentReconciler.releaseRoute(key),- triggerHint: (runtime, engine) => agentReconciler.triggerHint(runtime, engine),+ triggerHint: async (runtime, engine) => { await agentReconciler.triggerHint(runtime, engine) },log: (message) => console.log(message),})// A row restore could not look at keeps its pane for discovery to judge, but not to retire this boot.- if (summary.unsurveyed.length) restoreDegraded = true+ for (const agentId of summary.unsurveyed) restoreUnsurveyed.add(agentId)if (summary.restored.length || summary.failed.length || registry.rebootedSinceLastRun) {console.log(`[restore] restored ${summary.restored.length} · skipped ${summary.skipped.length} · failed ${summary.failed.length}`+ (registry.rebootedSinceLastRun ? ' · after reboot' : ''))}} catch (error) {- restoreDegraded = true+ restoreFailed = trueconsole.warn(`[restore] skipped · ${error instanceof Error ? error.message : error}`+ ' · agents keep their rows and come back on the next start')}@@ -3571,7 +3576,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const watchNewPane = createPaneWatcher({registry,announceSession,- triggerHint: (runtime, engine) => agentReconciler.triggerHint(runtime, engine),+ triggerHint: async (runtime, engine) => { await agentReconciler.triggerHint(runtime, engine) },captureTerminal,retainExitedSession,})@@ -4028,7 +4033,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {}))if (appVoiceFocus) autonomousDeviceService?.appFocus(appVoiceFocus.machineId, appVoiceFocus.agentId, appVoiceFocus.connId)if (autonomousDeviceService) backend.setAutonomousDeviceService(autonomousDeviceService)- autonomousDeviceDirect = startDevicePart('Wi-Fi device link', () => new AutonomousDeviceDirect({+ // No link without the service: a device it connected would be answered by nothing.+ autonomousDeviceDirect = autonomousDeviceService && startDevicePart('Wi-Fi device link', () => new AutonomousDeviceDirect({machineId: backend.machineId, label: hostname(),receive: (connId, frame, pairing) => backend.receiveDirectDevice(connId, frame, pairing),attach: (connId, send) => backend.attachDirectDevice(connId, send),@@ -4040,6 +4046,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {}, env.ADAPTER_DATA_DIR))backend.onDirectDeviceRevoked = fp => autonomousDeviceDirect?.revoked(fp)autonomousDeviceDirect?.start()+ devicePartsBuilt = true// Worktrees Harness made that no live or stopped harness uses and nothing would miss// (services/workspaces.ts): a few minutes after start, once restored agents are back in thediff --git a/cli/src/core/agents/discovery.spec.ts b/cli/src/core/agents/discovery.spec.tsindex bbf341a67..77c86f6bf 100644--- a/cli/src/core/agents/discovery.spec.ts+++ b/cli/src/core/agents/discovery.spec.ts@@ -20,7 +20,7 @@ const seen = (over: Partial<DiscoveredTerminalAgent> = {}): DiscoveredTerminalAgfunction setup(over: Partial<DiscoveryDeps> = {}) {const rows = new Map<string, RegisteredSession>()- let restoreDegraded = false+ let restoreDegraded: (agentId: string) => boolean = () => falseconst deps: DiscoveryDeps = {registry: {byRuntimeEngine: vi.fn(() => undefined),@@ -53,10 +53,10 @@ function setup(over: Partial<DiscoveryDeps> = {}) {stopHeartbeat: vi.fn(),retainExitedSession: vi.fn(),stoppedAgents: { finishResume: vi.fn() },- restoreDegraded: () => restoreDegraded,+ restoreDegraded: (agentId) => restoreDegraded(agentId),...over,}- return { deps, rows, handlers: createDiscoveryHandlers(deps), degrade: () => { restoreDegraded = true } }+ return { deps, rows, handlers: createDiscoveryHandlers(deps), degrade: (only?: string) => { restoreDegraded = (agentId) => only === undefined || agentId === only } }}const settle = () => new Promise((done) => setTimeout(done, 0))@@ -259,6 +259,18 @@ describe('discovery', () => {expect(run.deps.announceSession).toHaveBeenCalled()})+ it('keeps only the rows restore could not look at, and retires any other whose pane is gone', () => {+ // One row restore could not survey (a `ps` that timed out at boot) used to stop every pane closed+ // outside the app from being retired, for as long as the core ran.+ const run = setup()+ run.degrade('a2')+ run.handlers.onRemoved(row(), 'pane gone')+ expect(run.deps.forgetSession).toHaveBeenCalledWith('a1', { force: true })+ run.handlers.onRemoved({ ...row(), agentId: 'a2' }, 'pane gone')+ expect(run.deps.forgetSession).toHaveBeenCalledTimes(1)+ expect(run.deps.registry.setActive).toHaveBeenCalledWith('a2', false)+ })+it('records whether a row\'s terminal is available, announcing it when it becomes so', () => {const run = setup()run.handlers.onTerminalAvailability(row(), true)diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.tsindex 6f1e7ebf9..5588a73b4 100644--- a/cli/src/core/agents/discovery.ts+++ b/cli/src/core/agents/discovery.ts@@ -38,8 +38,9 @@ export interface DiscoveryDeps {stopHeartbeat: (sessionId: string) => voidretainExitedSession: (agent: RegisteredSession, announce: boolean) => voidstoppedAgents: Pick<StoppedAgentStore, 'finishResume'>- /** Whether restore did not run this boot: a missing pane then is one never rebuilt, not one closed. */- restoreDegraded: () => boolean+ /** Whether restore did not get to this agent this boot (it did not run, or could not look at its row):+ * its missing pane is then one never rebuilt, not one closed. */+ restoreDegraded: (agentId: string) => boolean}export function createDiscoveryHandlers({@@ -207,7 +208,7 @@ export function createDiscoveryHandlers({// would archive a row whose tmux pane was simply never rebuilt, and the person would have to// Open each one by hand; keeping it dormant leaves the next daemon — the fixed one — something// to restore.- if (restoreDegraded()) {+ if (restoreDegraded(agent.agentId)) {console.log(`[discovery] ${sid(agent.agentId)} kept · restore did not run this boot · ${reason}`)registry.setActive(agent.agentId, false)announceSession(agent)diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.tsindex 0f2dc9d48..3504a150b 100644--- a/cli/src/core/engines/hooks.spec.ts+++ b/cli/src/core/engines/hooks.spec.ts@@ -38,7 +38,7 @@ const hint = (paneId: string) => ({ backend: 'tmux' as const, paneId })function setup(onPane: Record<string, RegisteredSession> = {}, over: Partial<EngineHookDeps> = {}) {const deps: EngineHookDeps = {tmuxBackend: {},- agentReconciler: { triggerHint: vi.fn(async () => {}), trigger: vi.fn(async () => {}) } as unknown as EngineHookDeps['agentReconciler'],+ agentReconciler: { triggerHint: vi.fn(async () => true), trigger: vi.fn(async () => true) } as unknown as EngineHookDeps['agentReconciler'],registry: { byRuntimeEngine: vi.fn((runtime: { paneId: string }) => onPane[runtime.paneId]) } as unknown as EngineHookDeps['registry'],...over,}@@ -169,6 +169,24 @@ describe('which agent a hook belongs to', () => {expect(hook.answer()).toEqual(agent('a1', 200))})+ it('when discovery was too slow to open its agent, waits for the agent to appear on its pane', async () => {+ // A hook from an engine started by hand in a terminal: only a discovery pass opens its agent, and+ // the pass outran its deadline (a loaded machine). Nothing is on the pane yet, so nothing waited.+ const onPane: Record<string, RegisteredSession> = {}+ vi.mocked(processRows).mockResolvedValue(newEngine() as never)+ const slow = setup(onPane, { agentReconciler: { triggerHint: vi.fn(async () => false), trigger: vi.fn(async () => false) } as unknown as EngineHookDeps['agentReconciler'] })+ const onWait = vi.fn()+ const hook = ask(slow.hooks, ['%1'], onWait)+ await hook.waiting()+ await new Promise((resolve) => setTimeout(resolve, 250))+ expect(hook.answer()).toBeUndefined()+ expect(onWait).toHaveBeenCalledTimes(1)+ // The pass, done at last, opens the agent on the pane with the engine the hook came from.+ onPane['%1'] = agent('a1', 200)+ await hook.asked+ expect(hook.answer()).toEqual(agent('a1', 200))+ })+it('none when what is recorded is a process it does not come from, or the table cannot be read again', async () => {const onPane: Record<string, RegisteredSession> = { '%1': agent('a1') }vi.mocked(processRows).mockResolvedValue(newEngine() as never)diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.tsindex c60447957..bcce161bf 100644--- a/cli/src/core/engines/hooks.ts+++ b/cli/src/core/engines/hooks.ts@@ -117,7 +117,9 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry }: Enfor (const hint of runtimeHints ?? []) {if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId })}- for (const runtime of resolved) await agentReconciler.triggerHint(runtime, engine)+ // A pass that outran its deadline has not yet opened the agent a hook from a new engine belongs to.+ let overdue = false+ for (const runtime of resolved) if (!await agentReconciler.triggerHint(runtime, engine)) overdue = truelet found = await matchCaller(resolved, engine, callerPid)if (!found) return null@@ -128,7 +130,9 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry }: En// (round 23), and a restart's new conversation was never bound (round 24). While the agent on the// hook's pane has no live process recorded, the hook now waits for it to record one, and is matched// again against that: one rule for every relaunch, with nothing for any of them to remember to do.- if (!choice.agent && choice.reason === 'none' && found.unrecorded.length) {+ // So does one that came while discovery was too slow to open its agent: the agent appearing on the+ // pane is a change of its record too.+ if (!choice.agent && choice.reason === 'none' && (found.unrecorded.length || overdue)) {onWait?.()await recordChanged(resolved, engine)found = await matchCaller(resolved, engine, callerPid)diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex 2f84863d3..1dac1e999 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -6,7 +6,7 @@ import type { AutonomousDeviceInput } from '../lib/autonomous-device/input.js'import { deviceErrorText } from '../lib/deviceErrors.js'import type { RegisteredSession } from '../lib/registry.js'import type { SessionInputDelivery } from '../lib/sessionInput.js'-import type { TerminalActionResult } from '../lib/terminalTypes.js'+import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from '../lib/terminalTypes.js'import { CLAUDE_REWIND_LIST, CODEX_BROWSING_SCROLLBACK } from '../lib/__fixtures__/rewindPickers.js'import { createInput, createMessageRequest, deviceInputDeps, messageWriter, sessionInputDeps, type InputDeps } from './input.js'@@ -126,6 +126,24 @@ describe('the session input controller\'s dependencies', () => {expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual(['submit cx hi', 'submit a1 hi'])})+ it('reads the pane after its engine has answered, so a dialog opened during the wait is seen', async () => {+ const run = deps()+ const wired = sessionInputDeps(run.deps, () => lock(run.calls))+ const order: string[] = []+ // The check that waits for the engine (a probe timed out, a restart recording its engine), and a+ // permission prompt that opens while it waits.+ vi.mocked(run.deps.terminal.validateTerminal).mockImplementation(async () => { order.push('validate'); run.setPane(CLAUDE_PERMISSION); return true })+ vi.mocked(run.deps.terminal.captureTerminal).mockImplementation(async () => { order.push('capture'); return CLAUDE_PERMISSION })+ expect(await wired.inject('a1', 'hello')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'permission_open' })+ expect(order).toEqual(['validate', 'capture'])+ // No engine there: refused as a lease is, which the controller asks again, and the pane is not read.+ vi.mocked(run.deps.terminal.validateTerminal).mockImplementation(async () => false)+ order.length = 0+ expect(await wired.inject('a1', 'hello')).toEqual({ state: 'failed', dispatch: 'not_started', reason: TERMINAL_LEASE_REFUSED })+ expect(order).toEqual([])+ expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual([])+ })+it('writes a team turn only into a ready pane whose delivery still holds control', async () => {const run = deps()const wired = sessionInputDeps(run.deps, () => lock(run.calls))diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 861410990..dc79cbef3 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -19,7 +19,7 @@ import type { LiveEvent } from '../lib/normalize.js'import type { RegisteredSession } from '../lib/registry.js'import { SessionInputController, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'import { messageHold } from '../lib/messageHold.js'-import { terminalActionNotStarted, type TerminalActionResult } from '../lib/terminalTypes.js'+import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type TerminalActionResult } from '../lib/terminalTypes.js'import { Id } from '../teams/model.js'import { teamWriteHold } from '../teams/preflight.js'import type { TerminalControl } from './terminals/control.js'@@ -58,10 +58,16 @@ export interface InputDeps {* team's, which waits for a draft too). `submitTerminalAction` is called here and nowhere else in this* file, and input.spec.ts keeps it so.*/-export function messageWriter({ resolve, terminal: { captureTerminal, submitTerminalAction } }: Pick<InputDeps, 'resolve' | 'terminal'>) {+export function messageWriter({ resolve, terminal: { captureTerminal, validateTerminal, submitTerminalAction } }: Pick<InputDeps, 'resolve' | 'terminal'>) {return async (id: string, text: string, hold?: (session: RegisteredSession, capture: string | null) => string | null): Promise<TerminalActionResult> => {const session = resolve(id)if (!session) return terminalActionNotStarted('terminal agent is unavailable')+ // The engine first, then its screen. A check of the engine can wait, seconds, for an answer: a probe+ // a held event loop timed out, a restart still recording its new engine (TerminalBackendCoordinator+ // validateRuntime). Read before that wait, the screen was judged as it was then, and a permission+ // prompt opened meanwhile, or a new engine's first screen, took the paste and its Enter. An engine+ // not there is refused as a lease is, which the caller asks again.+ if (!await validateTerminal(session)) return terminalActionNotStarted(TERMINAL_LEASE_REFUSED)const capture = await captureTerminal(id)const reason = hold?.(session, capture) ?? messageHold(session.engine, capture)return reason ? terminalActionNotStarted(reason) : submitTerminalAction(id, text)diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.tsindex 4521759d9..60e5a6305 100644--- a/cli/src/core/transcripts/attach.spec.ts+++ b/cli/src/core/transcripts/attach.spec.ts@@ -330,6 +330,14 @@ describe('attaching a session', () => {await restarted.attach.attachSession(s)expect(restarted.deps.emit).not.toHaveBeenCalled()expect(log.mock.calls.some(([line]) => String(line).includes('left the turn open at attach as history'))).toBe(true)+ // Closed where the next message is read, too: its start must not first end a turn nobody saw start.+ expect(restarted.normalizers.turnStates.get(s.sessionId)?.turnOpen).toBe(false)+ expect(survived.normalizers.turnStates.get(s.sessionId)?.turnOpen).toBe(true)+ // Codex's own normalizer, likewise.+ const codex = session('codex', transcript([{ open: true }]))+ const resumed = setup({ relaunchMarks: { take: () => ({ offset: statSync(codex.transcriptPath!).size, engineStarted: true }) } })+ await resumed.attach.attachSession(codex)+ expect(resumed.normalizers.codexNormalizers.get(codex.sessionId)?.turnOpen).toBe(false)})it('replays a Claude Code first turn live when born after its agent, unless a held tail already delivered it', async () => {diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.tsindex 6fb891295..324a7576a 100644--- a/cli/src/core/transcripts/attach.ts+++ b/cli/src/core/transcripts/attach.ts@@ -419,6 +419,14 @@ export function createAttach({// interrupted message starting anew (core/transcripts/relaunch.ts).if (historyTurnOpen && !handover.hold && relaunch?.engineStarted) {console.log(`[agent] ${sid(session.agentId)} left the turn open at attach as history · it began before its engine was started again`)+ // Closed in the normalizer too, and as silently. Left open, the next message's start ended it first:+ // a turn_ended for a turn no client saw start (a "done" and its notification), a team's or the+ // orchestrator's delivery read as ended before it started, and the agent working until then.+ const folds: Array<Map<string, { closeTurn(): unknown }>> = [codexNormalizers, cursorNormalizers, museNormalizers, ampNormalizers,+ grokNormalizers, agyNormalizers, copilotNormalizers, piNormalizers, commandcodeNormalizers]+ for (const fold of folds) fold.get(session.sessionId)?.closeTurn()+ const state = turnStates.get(session.sessionId)+ if (state) { state.turnOpen = false; state.pendingTools.clear() }} else if (historyTurnOpen && !handover.hold) {const opened = historyEvents.findLast((event) => event.type === 'turn_started')if (opened) {diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.tsindex a90baca9d..589c3cfd2 100644--- a/cli/src/harnessd/master.spec.ts+++ b/cli/src/harnessd/master.spec.ts@@ -8,6 +8,7 @@ import {coreExecArgv, coreHandle, describeMasterStatus, heapLimitInArgv, masterDefaults, onProcessSignal, probeMaster, processExecve, processExit,readStatusFile, runMaster, supervisorOptions, trimLogEvery, writeStatusFile, type MasterStatusFile,} from './master.js'+import { ignoreLogWriteErrors } from '../lib/log.js'import { folderFingerprint } from './leanBundle.js'import { PROBE_ANSWER, RESUME_ENV, decodeResume, encodeResume, fingerprint, readMarker, writeMarker } from './reexec.js'import { DEFAULT_SUPERVISOR_OPTIONS, type ResumeState } from './supervisor.js'@@ -221,6 +222,36 @@ describe('coreHandle', () => {})// A real master over a real child: a few lines of JavaScript that behave like a core.+describe('a log that cannot grow', () => {+ // The master's stdout is the daemon's log file, on the disk everything else is on. A size limit stands+ // in for a full disk: the write fails the same way (EFBIG for ENOSPC), and the process must live on.+ const script = (guard: boolean) => `+ ${guard ? `import { ignoreLogWriteErrors } from ${JSON.stringify(new URL('../lib/log.ts', import.meta.url).pathname)}\nignoreLogWriteErrors()` : ''}+ const line = 'x'.repeat(1500)+ let n = 0+ const timer = setInterval(() => { console.log(line); if (++n === 30) { clearInterval(timer); process.exit(0) } }, 5)+ `+ const run = (guard: boolean): Promise<number | null> => {+ const dir = mkdtempSync(join(tmpdir(), 'harnessd-full-log-'))+ const file = join(dir, 'master.mts')+ writeFileSync(file, script(guard))+ const cli = new URL('../..', import.meta.url).pathname+ const child = spawn('/bin/sh', ['-c', `ulimit -f 4; exec "$0" --import tsx "$1" > "$2" 2>&1`, process.execPath, file, join(dir, 'harness.log')], { cwd: cli, stdio: 'ignore' })+ return new Promise((resolve) => child.once('exit', (code) => { rmSync(dir, { recursive: true, force: true }); resolve(code) }))+ }++ it('has its failed writes dropped', () => {+ const stream = new EventEmitter()+ ignoreLogWriteErrors([stream])+ expect(() => stream.emit('error', Object.assign(new Error('ENOSPC: no space left on device, write'), { code: 'ENOSPC' }))).not.toThrow()+ })++ it('is not what stops the master: a write that fails is dropped', async () => {+ expect(await run(false)).toBe(1)+ expect(await run(true)).toBe(0)+ }, 30_000)+})+describe('runMaster', () => {let dir: stringbeforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'harnessd-master-')) })@@ -273,6 +304,32 @@ describe('runMaster', () => {expect(updates).toEqual([])})+ it('carries on, without a pid file, when the disk will not take one', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const pidFile = join(dir, 'no-such-folder', 'adapter.pid')+ const core = join(dir, 'core.cjs')+ writeFileSync(core, `+ process.send({ type: 'harnessd:bound', protocol: 2, port: 1 })+ process.send({ type: 'harnessd:ready' })+ setInterval(() => process.send({ type: 'harnessd:heartbeat', rssBytes: 1, heapUsedBytes: 1, loopDelayMs: 0 }), 50)+ process.on('SIGTERM', () => process.exit(0))+ `)+ const exits: number[] = []+ const signals = new Map<string, () => void>()+ const supervisor = runMaster({+ nodePath: process.execPath, execArgv: [], scriptPath: core, pidFile,+ restoreUpdate: () => {}, confirmUpdate: () => {},+ exit: (code) => exits.push(code), onSignal: (signal, listener) => signals.set(signal, listener),+ })+ try {+ await until('the core to be running', () => supervisor.status().state === 'running')+ expect(log.mock.calls.map((call) => String(call[0]))).toContainEqual(expect.stringContaining('[harnessd] could not write the pid file: ENOENT'))+ signals.get('SIGTERM')!()+ await until('the master to finish', () => exits.length > 0)+ expect(exits).toEqual([0])+ } finally { log.mockRestore() }+ })+it('records its status as it goes, and starts the core with the heap limit its budget is a share of', async () => {const pidFile = join(dir, 'adapter.pid')const statusFile = join(dir, 'harnessd-status.json')diff --git a/cli/src/harnessd/master.ts b/cli/src/harnessd/master.tsindex 34dfb0d15..488adc877 100644--- a/cli/src/harnessd/master.ts+++ b/cli/src/harnessd/master.ts@@ -7,7 +7,7 @@ import { spawn, type ChildProcess } from 'node:child_process'import { randomBytes } from 'node:crypto'import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { performance } from 'node:perf_hooks'-import { trimLogFile, ts } from '../lib/log.js'+import { ignoreLogWriteErrors, trimLogFile, ts } from '../lib/log.js'import { folderFingerprint } from './leanBundle.js'import { leanServices } from './leanServices.js'import { platformFromEnv, type PlatformName } from './platform.js'@@ -226,7 +226,9 @@ export function probeMaster(config: { env: NodeJS.ProcessEnv; execArgv: string[]}}+export function runMaster(config: MasterConfig): Supervisor {+ ignoreLogWriteErrors()const { env: given, exit, onSignal, execve } = masterDefaults(config)process.title = 'harnessd'// What the master this process was a moment ago handed on, if it was one (./reexec.ts). Taken out of@@ -323,7 +325,11 @@ export function runMaster(config: MasterConfig): Supervisor {writeStatus: (status) => { if (config.statusFile) writeStatusFile(config.statusFile, { ...status, masterPid: process.pid, ...(platform ? { platform } : {}) }) },setTimer: (run, ms) => setTimeout(run, ms),clearTimer: (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),- claimPidFile: () => writeFileSync(config.pidFile, `${process.pid}\n`),+ // On a full disk the claim fails, and the master carries on without it: it was thrown out of the+ // core's `bound` message, and took the master down.+ claimPidFile: () => {+ try { writeFileSync(config.pidFile, `${process.pid}\n`) } catch (error) { log(`[harnessd] could not write the pid file: ${(error as Error).message}`) }+ },releasePidFile: () => { if (readPid() === process.pid) rmSync(config.pidFile, { force: true }) },restoreUpdate: config.restoreUpdate,confirmUpdate: config.confirmUpdate,diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 1b5c83510..69c0cf2e5 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -832,6 +832,14 @@ describe('hook notify terminal scope', () => {expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'maybe-alive' }])})+ /** What the daemon chose for an agent and keeps on its row, beyond what the process shows (registry.ts+ * `register()` carries every one): a hook while the daemon is down must not be the write that drops it. */+ const CHOSEN = {+ dsh: 'cad-designer', dshRuntime: '/tmp/dsh/cad-designer/1.2.0', agent: 'reviewer', permissionMode: 'plan',+ subscriptionModel: 'opus', defaultName: 'Claude Code 3', gridWebSearch: true,+ closePlan: { id: 'plan-1', requestedAt: 1_790_000_000_001, identity: 'claude\u0000agent-created', state: 'waiting' },+ }+it('carries what the daemon chose at launch through an offline re-register', async () => {// A hook arriving while the daemon is down rebuilds the row. The grid launch (key included), the// Codex profile, the bypass flag and the observed grid are not on the process or in the hook body@@ -878,6 +886,7 @@ describe('hook notify terminal scope', () => {// When an app last opened it — every app's "last used" order reads this, so a hook that lands// while the daemon is down must not be the write that forgets it.lastOpenedAt: 1_790_000_000_000,+ ...CHOSEN,}]))await runHook({@@ -898,8 +907,19 @@ describe('hook notify terminal scope', () => {gridLaunch,bypassPermission: true,lastOpenedAt: 1_790_000_000_000,+ ...CHOSEN,})expect(registry[0]).not.toHaveProperty('launch')++ // A row whose launch was a resume only: as the daemon has it, a hook ends that launch.+ const rows = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))+ rows[0] = { ...rows[0], resumeOnly: true, launch: { state: 'starting' } }+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify(rows))+ await runHook({+ port: 9, tmuxPane: '%7', processEngine: 'claude', dataDir, claudeProjectsDir,+ input: { hook_event_name: 'UserPromptSubmit', session_id: 'session-1', transcript_path: transcriptPath, cwd: '/tmp/demo', prompt: 'next' },+ })+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))[0]).toMatchObject({ resumeOnly: true, launch: { state: 'ready' }, ...CHOSEN })})it('an offline re-register of the session a row already holds keeps the row\'s folder', async () => {diff --git a/cli/src/lib/dialogEnd.ts b/cli/src/lib/dialogEnd.tsindex ae950529f..dcabcb622 100644--- a/cli/src/lib/dialogEnd.ts+++ b/cli/src/lib/dialogEnd.ts@@ -27,8 +27,10 @@ export const QUESTION_FOOTER_RE = /enter to (select|confirm|submit|lock)|enter\s* Command Code `↑/↓ navigate · enter select · ctrl+e explain`. Proximity to the rows is what makes this* a guard and not a search: it must sit within a few lines UNDER them. */// Claude's plan review footer changed from Esc/Tab hints to-// "shift+tab to approve with this feedback" plus ctrl+g.-export const PERMISSION_FOOTER_RE = /\besc\b|enter\s+select|ctrl\+e|shift\+tab\s+to\s+approve/i+// "shift+tab to approve with this feedback" plus ctrl+g. Never the spinner of a turn at work, which sits+// right under its output in every engine (`esc to interrupt`): a numbered list in that output read as a+// permission prompt, and a message sent mid-turn was held for one that was not there.+export const PERMISSION_FOOTER_RE = /\besc\b(?! to interrupt)|enter\s+select|ctrl\+e|shift\+tab\s+to\s+approve/i/** The footers only an engine's own reader anchors on: devin `↵ select` / `↵ confirm`, grok `Enter:submit`* / `1/3:select`, agy and grok `navigate`, muse and amp `↑/↓ to move` / `↑/↓/j/k move`. */diff --git a/cli/src/lib/log.ts b/cli/src/lib/log.tsindex a1507db6a..f65de6a7b 100644--- a/cli/src/lib/log.ts+++ b/cli/src/lib/log.ts@@ -141,3 +141,18 @@ export function logFrame(direction: '→' | '←', audience: string, frame: { tyif (typeof payload.error === 'string') bits.push(`error=${payload.error}`)console.log(`[frame] ${direction} ${audience} ${type}${bits.length ? ` · ${bits.join(' · ')}` : ''}`)}++/**+ * A log write that fails is dropped, never fatal.+ *+ * The master's stdout and stderr are the daemon's log file (`harness start`, launchd's StandardOutPath,+ * systemd's `append:`), on the disk everything else is on. Node writes a file stdout synchronously, and a+ * write that fails there, on a full disk (ENOSPC) or past a size limit (EFBIG), is an 'error' event the+ * stream emits after `console.log` has returned; with no listener it is thrown, and the master died of+ * it: no master and no core until the disk had room, with a re-exec marker left to roll a good update+ * back on the next start. The same for a service, which shares the file.+ */+export function ignoreLogWriteErrors(streams: Pick<NodeJS.EventEmitter, 'on'>[] = [process.stdout, process.stderr]): void {+ for (const stream of streams) stream.on('error', dropLogWriteError)+}+function dropLogWriteError(): void { /* the line is lost; the process lives */ }diff --git a/cli/src/lib/machineNames.spec.ts b/cli/src/lib/machineNames.spec.tsindex 1ece555b5..6f3c0ec3e 100644--- a/cli/src/lib/machineNames.spec.ts+++ b/cli/src/lib/machineNames.spec.ts@@ -22,7 +22,14 @@ describe('the names a machine has gone by', () => {it('owns the name it has at start, in full and as its first part, in any case', () => {const names = createMachineNames(() => 'MacBook.lan')for (const title of ['macbook.lan', 'MacBook.lan', 'MACBOOK', 'macbook']) expect(names.owns(title), title).toBe(true)- for (const title of ['MacBook.local', 'Fix the login page', 'lan']) expect(names.owns(title), title).toBe(false)+ for (const title of ['Fix the login page', 'lan', 'MacBook2.lan', 'macbook pro.lan']) expect(names.owns(title), title).toBe(false)+ })++ it('owns its name under another network, which a daemon started since has never seen it on', () => {+ // Agents made on the home network keep their panes' titles across an update made on another.+ const names = createMachineNames(() => 'MacBook-Pro.local')+ for (const title of ['MacBook-Pro.lan', 'macbook-pro.example.com']) expect(names.owns(title), title).toBe(true)+ for (const title of ['MacBook-Pro-2.lan', 'MacBook-Pro is ready', 'MacBook-Pro.lan: build']) expect(names.owns(title), title).toBe(false)})it('keeps the name it had after it moves on: a pane made under it still carries it', () => {diff --git a/cli/src/lib/machineNames.ts b/cli/src/lib/machineNames.tsindex 8e8836877..b536f2b59 100644--- a/cli/src/lib/machineNames.ts+++ b/cli/src/lib/machineNames.ts@@ -11,7 +11,8 @@** So the name is read again on every title sweep and whenever the daemon has tmux make a pane, both a* syscall, and every name read is kept: a pane made under the old name still carries it after the- * machine has moved on. Kept to the last MACHINE_NAMES_KEPT names seen, so a machine that roams many+ * machine has moved on. A daemon started since knows none of the old names, so a host name is also+ * the machine's when its first part is: the same laptop, on another network. Kept to the last MACHINE_NAMES_KEPT names seen, so a machine that roams many* networks over weeks holds a few dozen strings, not one per network forever.*/import { readFileSync } from 'node:fs'@@ -19,6 +20,9 @@ import { hostname } from 'node:os'export const MACHINE_NAMES_KEPT = 16+/** A host name with a domain: `macbook-pro.lan`, `studio.local`, `box.example.com`. */+const HOST_NAME = /^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/+export interface MachineNames {/** Reads the machine's name now and keeps it among the names it has had. */observe(): void@@ -50,7 +54,16 @@ export function createMachineNames(read: () => string, kept = MACHINE_NAMES_KEPTforms = new Set([...names].flatMap((full) => [full, full.split('.')[0]!]).filter(Boolean))}observe()- return { observe, owns: (title) => forms.has(title.toLowerCase()) }+ return {+ observe,+ owns: (title) => {+ const name = title.toLowerCase()+ // The same machine on another network than any this daemon has seen it on: `MacBook-Pro.lan`, a+ // pane made before a restart on `MacBook-Pro.local`. Only a title shaped as a host name, so one+ // that is a sentence is never refused for starting with the machine's name.+ return forms.has(name) || (HOST_NAME.test(name) && forms.has(name.split('.')[0]!))+ },+ }}/**diff --git a/cli/src/lib/messageHold.spec.ts b/cli/src/lib/messageHold.spec.tsindex 98bba4f78..5c82c3080 100644--- a/cli/src/lib/messageHold.spec.ts+++ b/cli/src/lib/messageHold.spec.ts@@ -38,6 +38,64 @@ describe('what a message is not typed into', () => {}})+ it('is a permission prompt whose rows wrapped in a narrow pane, read by its question alone', () => {+ // Ink wraps a long row onto a line of its own, which ends the run of numbered rows the prompt is+ // otherwise read by. Claude Code's edit, write and fetch prompts then went unseen, and the Enter+ // after the paste approved the edit.+ const edit = fixture('permission-claude-edit.txt').replace('Yes, allow all edits during this session ', 'Yes, allow all edits during this\n session ')+ expect(edit).not.toBe(fixture('permission-claude-edit.txt'))+ expect(messageHold('claude', edit)).toBe('permission_open')+ const fetch = [+ '\u001b[38;5;239m❯ \u001b[38;5;231msummarise https://example.com\u001b[39m',+ '',+ '⏺ Fetch(https://example.com)',+ RULE,+ ' Fetch',+ ' https://example.com',+ ' Do you want to allow Claude to fetch this content?',+ ' ❯ 1. Yes',+ ' 2. Yes, and don\u2019t ask again for',+ ' example.com',+ ' 3. No, and tell Claude what to do differently',+ ' (esc)',+ ].join('\n')+ expect(messageHold('claude', fetch)).toBe('permission_open')+ const plan = fixture('permission-claude-plan.txt')+ expect(messageHold('claude', plan)).toBe('permission_open')+ })++ it('is not a numbered list in the output of a turn at work, over its spinner', () => {+ const working = [+ '❯ tidy up the release script',+ '',+ '⏺ Here is the plan:',+ ' 1. Run the existing tests first',+ ' 2. Rename the helper',+ ' 3. Stop publishing the debug build',+ '',+ '✻ Pondering… (12s · ↓ 1.2k tokens · esc to interrupt)',+ '',+ RULE, '❯ ', RULE, ' ? for shortcuts',+ ].join('\n')+ expect(messageHold('claude', working)).toBeNull()+ const codex = ['› tidy up the release script', '', '• Plan:', ' 1. Run the existing tests first', ' 2. Stop publishing the debug build', '', '◦ Working (5s • esc to interrupt)', '', '› ', '', ' ? for shortcuts'].join('\n')+ expect(messageHold('codex', codex)).toBeNull()+ })++ it('is not a draft or an echo that asks a question of its own', () => {+ expect(messageHold('claude', CLAUDE_PROMPT.replace('Try "fix lint errors"', 'Do you want to add tests? Would you like to proceed?'))).toBeNull()+ const answered = [+ '❯ Do you want to rename the module?',+ '',+ '⏺ Renamed it. Do you want to run the tests too?',+ RULE,+ '❯ ',+ RULE,+ ' ? for shortcuts',+ ].join('\n')+ expect(messageHold('claude', answered)).toBeNull()+ })+it('is a question, which is answered through its own path', () => {for (const [engine, name] of [['claude', 'question-single.txt'], ['claude', 'question-multi.txt'], ['codex', 'question-codex.txt']] as const) {expect(messageHold(engine, fixture(name)), name).toBe('question_open')@@ -47,6 +105,10 @@ describe('what a message is not typed into', () => {it('is, in Claude Code and Codex, a menu, a picker for a point to rewind to, or Claude Code\'s transcript view', () => {expect(messageHold('codex', CODEX_MODEL_MENU)).toBe('menu_open')expect(messageHold('claude', CLAUDE_REWIND_LIST)).toBe('rewind_picker_open')+ // In a pane narrower than its body line, which wraps.+ const narrow = CLAUDE_REWIND_LIST.replace(' Restore the code and/or conversation to the point before', ' Restore the code and/or conversation to\n the point before')+ expect(narrow).not.toBe(CLAUDE_REWIND_LIST)+ expect(messageHold('claude', narrow)).toBe('rewind_picker_open')expect(messageHold('claude', CLAUDE_REWIND_CONFIRM)).toBe('rewind_picker_open')expect(messageHold('codex', CODEX_BROWSING_FULLSCREEN)).toBe('rewind_picker_open')expect(messageHold('codex', CODEX_BROWSING_SCROLLBACK)).toBe('rewind_picker_open')diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.tsindex 27ad07ba1..16bfddce9 100644--- a/cli/src/lib/runtimeProfileController.ts+++ b/cli/src/lib/runtimeProfileController.ts@@ -345,7 +345,9 @@ export function paneModal(engine: RegisteredSession['engine'], capture: string):const currentUi = currentPaneUi(rawLines, latestPromptLine(rawLines, promptMarker(engine)))const takeover = takeoverIn(engine, capture, currentUi)if (takeover) return takeover- if (PERMISSION_UI.test(currentUi)) return 'permission'+ // Below the prompt line: that line is the composer, or the echo of the last message, and either can+ // hold anything a person typed.+ if (PERMISSION_UI.test(currentUi.slice(currentUi.indexOf('\n') + 1))) return 'permission'return DIALOG_UI.test(currentUi.replace(/Starting MCP servers?/gi, '')) ? 'menu' : null}@@ -428,7 +430,15 @@ const CLAUDE_HISTORY_SEARCH = /^\s*(?:search prompts|no matching prompt): /const DIALOG_UI = /Select Model(?: and Effort)?|Select Reasoning Level|Advanced Reasoning|Available models|Models matching|Edit Parameters|Type to filter.*Tab to edit|Esc to go back|Press enter to confirm|Do you want to proceed|Allow this action|permission required|Starting MCP servers?/i/** The approval prompts among them. */-const PERMISSION_UI = /Do you want to proceed|Allow this action|permission required/i+/**+ * An approval prompt's question. Claude Code asks "Do you want to proceed?", "Do you want to make this+ * edit to <file>?", "Do you want to allow Claude to fetch this content?", "Do you want to <verb> <target>?"+ * for the other tools, and "Would you like to proceed?" over a plan (2.1.289); Codex asks "Would you like+ * to run the following command?" and the like. The rows under it are read too (askQuestion.ts), but a+ * row wrapped in a narrow pane breaks that reading, and the question alone must still hold a message:+ * Enter approves the first row. Asked only below the prompt line, so never of what a person typed.+ */+const PERMISSION_UI = /\bDo you want to\b|\bWould you like to (?:proceed|run|make|apply|allow)\b|Allow this action|permission required/i/*** Codex browsing its own transcript: Esc twice on an empty composer, and its footer row reads@@ -452,7 +462,9 @@ const CODEX_TRANSCRIPT_BROWSING = /^\s*Browsing(?: transcript)?(?:\s+·|\s*$)/m* A message pasted into it is dropped either way. Its focused row is drawn `❯ (current)` in italics,* which read as an empty, idle prompt.*/-const CLAUDE_REWIND_BODY = /^(?:Restore the code and\/or conversation to the point before|Restore and fork the conversation to the point before|Confirm you want to restore|Nothing to rewind to yet)/+// Their opening words only: a pane narrower than a line wraps the rest onto the next, and the menu went+// unseen, its Enter picking a message (with checkpoints off, rewinding to it).+const CLAUDE_REWIND_BODY = /^(?:Restore the code\b|Restore and fork\b|Confirm you want to restore\b|Nothing to rewind to\b)/function claudeRewindMenuOpen(capture: string): boolean {const lines = stripAnsi(capture).replace(/\u00a0/g, ' ').split('\n').map((line) => line.trim())diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex c5ec485b5..8ba1cf3d3 100644--- a/cli/src/lib/sessionInput.spec.ts+++ b/cli/src/lib/sessionInput.spec.ts@@ -1,3 +1,6 @@+import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'import { afterEach, describe, expect, it, vi } from 'vitest'import { SessionInputController } from './sessionInput.js'import type { RegisteredSession } from './registry.js'@@ -468,6 +471,59 @@ describe('SessionInputController', () => {controller.forget('s1')})+ describe('a dialog over the composer when the turn has not been seen to start', () => {+ // Recorded on Claude Code 2.1.232: the message was taken, and its turn stopped at a Bash approval.+ // Above the prompt, the transcript's echo of the message, which used to read as an unsent draft.+ const screen = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '__fixtures__', 'permission-claude.txt'), 'utf8')+ const message = 'Run this exact command with Bash, nothing else: curl -s https://api.coingecko.com/api/v3/simple/price?ids=bitcoin'++ it('never presses Enter into a permission prompt, and takes it as the message accepted', async () => {+ vi.useFakeTimers()+ const sendKey = vi.fn(async () => true), onError = vi.fn(), onDelivery = vi.fn()+ let pasted = false+ const controller = new SessionInputController({+ getSession: () => session('claude'), validateRuntime: async () => true, onDelivery,+ inject: async () => { pasted = true; return true }, sendKey, capture: async () => pasted ? screen : '❯ ', onError,+ })+ controller.submit('s1', message)+ await vi.advanceTimersByTimeAsync(60_000)+ expect(sendKey).not.toHaveBeenCalled()+ expect(onError.mock.calls).toEqual([])+ controller.forget('s1')+ })++ it('reports a delivery with a receipt as unknown, still without an Enter', async () => {+ vi.useFakeTimers()+ const sendKey = vi.fn(async () => true), onError = vi.fn(), onDelivery = vi.fn()+ let pasted = false+ const controller = new SessionInputController({+ getSession: () => session('claude'), validateRuntime: async () => true, onDelivery,+ inject: async () => { pasted = true; return true }, sendKey, capture: async () => pasted ? screen : '❯ ', onError,+ })+ controller.submit('s1', message, 'delivery-1')+ await vi.advanceTimersByTimeAsync(60_000)+ expect(sendKey).not.toHaveBeenCalled()+ expect(onDelivery).toHaveBeenLastCalledWith({ sessionId: 's1', deliveryId: 'delivery-1', state: 'unknown', reason: 'dispatch_ambiguous' })+ controller.forget('s1')+ })++ it('never presses Enter into a menu either, and says the delivery could not be confirmed', async () => {+ vi.useFakeTimers()+ const sendKey = vi.fn(async () => true), onError = vi.fn()+ // Codex browsing its transcript (0.160): Enter would rewind the conversation to the prompt in view.+ const browsing = `› ${message}\n\n Browsing transcript · ↑↓/jk scroll · ←→/hl prompts · ↵ rewind · esc back\n`+ const controller = new SessionInputController({+ getSession: () => session('codex'), validateRuntime: async () => true,+ inject: async () => true, sendKey, capture: async () => browsing, onError,+ })+ controller.submit('s1', message)+ await vi.advanceTimersByTimeAsync(60_000)+ expect(sendKey).not.toHaveBeenCalled()+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))+ controller.forget('s1')+ })+ })+it('reports uncertainty without blindly pressing Enter when the terminal shows no composer', async () => {vi.useFakeTimers()const sendKey = vi.fn(async () => true)diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex dbfc1ba67..46df3ee7c 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -1,7 +1,7 @@import { createHash } from 'crypto'import type { RegisteredSession } from './registry.js'import { sid } from './log.js'-import { isMessageHold, messageHoldText, type MessageHold } from './messageHold.js'+import { isMessageHold, messageHold, messageHoldText, type MessageHold } from './messageHold.js'import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'const MAX_QUEUE_ITEMS = 8@@ -625,6 +625,7 @@ export class SessionInputController {if (session.engine === 'cursor') {const capture = await this.deps.capture?.(session.agentId)if (!state.awaitingFingerprint || state.turnOpen) return+ if (this.dialogOverComposer(sessionId, session, state, capture)) returnconst draftPending = !!capture && cursorComposerContains(capture, state.awaitingContent ?? '')if (state.ambiguousDispatch && !draftPending) {this.failAmbiguousSubmission(sessionId, state)@@ -663,6 +664,7 @@ export class SessionInputController {// claude/codex/commandcode: verify against the terminal before pressing Enter again or declaring failure.const capture = await this.deps.capture?.(session.agentId)if (!state.awaitingFingerprint || state.turnOpen) return+ if (this.dialogOverComposer(sessionId, session, state, capture)) return// Command Code writes the user line to its transcript only once the model has finished THINKING, so// the turn_started this used to wait for can be half a minute late on a real task — and the user// watched the terminal accept the message and start working while the device claimed it had been@@ -746,6 +748,28 @@ export class SessionInputController {this.armSubmitCheck(sessionId, session, state)}+ /**+ * A dialog, a menu or a view over the composer, settled without an Enter. The prompt line the retry+ * reads is then the transcript's echo of this very message, not a draft, and an Enter answers the+ * dialog: on a permission prompt, "1. Yes", a command nobody approved. A prompt or a question the+ * agent asks means the message was taken and its turn has reached a tool; anything else leaves it+ * unknown, as does any delivery with a receipt, which the pane alone cannot settle.+ */+ private dialogOverComposer(sessionId: string, session: RegisteredSession, state: InputState, capture: string | null | undefined): boolean {+ const hold = capture ? messageHold(session.engine, capture) : null+ if (!hold) return false+ if (state.deliveryId || (hold !== 'permission_open' && hold !== 'question_open')) {+ this.failAmbiguousSubmission(sessionId, state)+ return true+ }+ console.log(`[inject] ${sid(sessionId)} accepted (${hold} on screen) · engine=${session.engine}`)+ state.awaitingFingerprint = null+ state.awaitingContent = null+ state.observes = 0+ state.ambiguousDispatch = false+ return true+ }+private failAmbiguousSubmission(sessionId: string, state: InputState): void {this.finishDelivery(sessionId, state, 'unknown', 'dispatch_ambiguous')state.awaitingFingerprint = nulldiff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.tsindex a8dc9fc70..5688f761c 100644--- a/cli/src/lib/terminalAgentReconciler.spec.ts+++ b/cli/src/lib/terminalAgentReconciler.spec.ts@@ -669,13 +669,14 @@ describe('a pass with a deadline', () => {current: () => [session()], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved, probe: probed, passDeadlineMs: 50,})- // Before, this never returned: not to a hook waiting to bind, nor to anything after it.- await reconciler.triggerHint(tmux, 'claude')+ // Before, this never returned: not to a hook waiting to bind, nor to anything after it. It says the+ // pass was not done, so the hook knows to wait for its agent another way.+ await expect(reconciler.triggerHint(tmux, 'claude')).resolves.toBe(false)expect(warn).toHaveBeenCalledWith('[discovery] the terminal probe has not answered in 50 ms; this pass is given up, every agent kept as it is')expect(onRemoved).not.toHaveBeenCalled()expect(onDormant).not.toHaveBeenCalled()answer = probe(available())- await reconciler.trigger()+ await expect(reconciler.trigger()).resolves.toBe(true)expect(probed).toHaveBeenCalledTimes(2)// The hint the given-up pass did not use is still there for the one that answered.expect(probed.mock.calls[1]).toEqual([new Map([[terminalRouteKey(tmux), 'claude']])])diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.tsindex ca9ae2a20..7e490d586 100644--- a/cli/src/lib/terminalAgentReconciler.ts+++ b/cli/src/lib/terminalAgentReconciler.ts@@ -174,7 +174,8 @@ export class TerminalAgentReconciler {this.timer = null}- triggerHint(runtime: TerminalRuntimeRef, engine: AgentEngine): Promise<void> {+ /** Asks for a pass that knows `engine` is starting in `runtime`'s pane. As [trigger]. */+ triggerHint(runtime: TerminalRuntimeRef, engine: AgentEngine): Promise<boolean> {this.hints.set(terminalRouteKey(runtime), engine)return this.trigger()}@@ -250,23 +251,30 @@ export class TerminalAgentReconciler {})}- trigger(): Promise<void> {+ /** Asks for a pass, and resolves once it is done: true, or false when the pass outran its deadline+ * ([RECONCILE_PASS_DEADLINE_MS]) and the caller goes on without what it would have found. */+ trigger(): Promise<boolean> {this.pending = true// Return promptly to startup hooks: waiting for start() here can hold up the very engines// restore is trying to launch. The opening pass consumes every retained hint after restore.- if (this.waitingForStart) return Promise.resolve()+ if (this.waitingForStart) return Promise.resolve(true)if (!this.inFlight) this.inFlight = this.drain().finally(() => { this.inFlight = null })return this.waitFor(this.inFlight)}/** A pass, waited for until the pass deadline and no longer: see [RECONCILE_PASS_DEADLINE_MS]. */- private async waitFor(pass: Promise<void>): Promise<void> {- if (await withinDeadline(pass, this.passDeadlineMs) !== GIVEN_UP) return- if (this.overdue === pass) return- this.overdue = pass- console.warn(`[discovery] a pass has run for ${this.passDeadlineMs} ms; whoever waits for it goes on without it`)+ private async waitFor(pass: Promise<void>): Promise<boolean> {+ // Done in time, but on a probe it gave up: it found nothing either.+ if (await withinDeadline(pass, this.passDeadlineMs) !== GIVEN_UP) return !this.probeGivenUp+ if (this.overdue !== pass) {+ this.overdue = pass+ console.warn(`[discovery] a pass has run for ${this.passDeadlineMs} ms; whoever waits for it goes on without it`)+ }+ return false}private overdue: Promise<void> | null = null+ /** Whether the last pass gave up on its probe. */+ private probeGivenUp = falseprivate get passDeadlineMs(): number { return this.deps.passDeadlineMs ?? RECONCILE_PASS_DEADLINE_MS }private async drain(): Promise<void> {@@ -300,6 +308,7 @@ export class TerminalAgentReconciler {this.deps.daemonPid ?? process.pid,hints,), this.passDeadlineMs)+ this.probeGivenUp = probe === GIVEN_UPif (probe === GIVEN_UP) {console.warn(`[discovery] the terminal probe has not answered in ${this.passDeadlineMs} ms; this pass is given up, every agent kept as it is`)returndiff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.tsindex f2da6fb90..95ec3025d 100644--- a/cli/src/lib/terminalBackendCoordinator.spec.ts+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts@@ -248,6 +248,22 @@ describe('TerminalBackendCoordinator', () => {expect(tmuxBackend.validate).toHaveBeenLastCalledWith(tmux, expect.objectContaining({ processIdentity: current.processIdentity }))})+ it('does not hold a lease to an engine a restart replaced while the lease was checked', async () => {+ const current = session()+ current.runtimes = [tmux]+ let live = 42+ const tmuxBackend = { ...backend('tmux:default', vi.fn()), validate: vi.fn(async (_runtime: TerminalRuntimeRef, expected: { processIdentity?: { pid: number } }) =>+ expected.processIdentity?.pid === live ? { state: 'alive' as const } : { state: 'gone' as const, reason: 'process changed under tmux pane', replaced: true as const }) }+ // The restart records its new engine on the row while the check waits.+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'], {+ unknownRetryMs: [10], sleep: async () => { current.processIdentity = { pid: 44, executable: 'claude', startMarker: 'Sat Aug 15 10:02:00 2026' } },+ })+ const acquired = await coordinator.acquireLease(current)+ if (acquired.state !== 'succeeded') throw new Error('no lease')+ live = 44+ await expect(coordinator.validateLease(acquired.value, current)).resolves.toBe(false)+ })+it('waits on a terminal with no engine in it while a restart is replacing that engine', async () => {const answers = [{ state: 'gone' as const, reason: 'no claude process under pane %1' }, { state: 'alive' as const }]const { coordinator } = patient(async () => answers.shift()!)diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.tsindex 9c4e88434..2e371c7ca 100644--- a/cli/src/lib/terminalBackendCoordinator.ts+++ b/cli/src/lib/terminalBackendCoordinator.ts@@ -195,7 +195,10 @@ export class TerminalBackendCoordinator {if (!this.leaseIsCurrent(lease, session)) return falseconst backend = this.backendFor(lease.runtime)if (!backend) return false- return (await this.validateRuntime(backend, lease.runtime, session)).state === 'alive'+ // Asked again after the check: it waits while a restart records its new engine, and then answers+ // `alive` for THAT engine, which this lease was not taken for. Kept, a question's answer went on+ // being keyed through it into the new engine's composer.+ return (await this.validateRuntime(backend, lease.runtime, session)).state === 'alive' && this.leaseIsCurrent(lease, session)}async capture(session: RegisteredSession, options?: TerminalCaptureOptions): Promise<TerminalReadResult<string>> {diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 57d2d9851..d7096046f 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -11,7 +11,7 @@ import { env } from './config/env.js'import { ensureUtf8Locale } from './lib/childLocale.js'import { readOrMintComputerId } from './lib/computerIdentity.js'import { localSocketPath } from './lib/localSocket.js'-import { installTimestampedConsole } from './lib/log.js'+import { ignoreLogWriteErrors, installTimestampedConsole } from './lib/log.js'import type { ServiceProcess } from './services/process.js'export interface ServiceProcessOptions {@@ -46,6 +46,8 @@ export async function startServiceProcess(name: string | undefined, deps: Servicreturn exit(2)}process.title = `harnessd ${name}`+ // Its lines share the daemon's log with the master's: a write a full disk refuses is dropped, not fatal.+ ignoreLogWriteErrors()// As every daemon process did at load: a service that runs `ps` or `git` must not get mangled output.ensureUtf8Locale()// Its lines go to the daemon's log between the core's and the master's, which are stamped: unstamped,