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
Core boundary, part 12: device faults never disconnect the desktop, and messages are written one at a time (#739)
Dee6bcdafb16db6
diff --git a/cli/e2e/edges.e2e.ts b/cli/e2e/edges.e2e.tsnew file mode 100644index 000000000..d85b5f552--- /dev/null+++ b/cli/e2e/edges.e2e.ts@@ -0,0 +1,132 @@+/**+ * Everyday edges of the core, for Claude Code and Codex, on the real daemon: folders whose names are+ * not plain ASCII, a folder that is not there, a long message and messages that are not plain ASCII,+ * messages sent faster than an agent can answer, forking an agent, and renaming one.+ */+import { mkdirSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++type Engine = 'claude' | 'codex'+const engines: Engine[] = ['claude', 'codex']++const row = async (client: LocalClient, agentId: string) =>+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)+ .find((agent) => agent.id === agentId)+const bound = (client: LocalClient, agentId: string) =>+ until(`${agentId.slice(0, 8)} to bind its conversation`, async () => {+ const agent = await row(client, agentId)+ return agent?.sessionId && agent.status === 'active' ? agent : null+ }, 60_000, 500)+async function create(daemon: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<string> {+ const cwd = join(daemon.projectsDir, folder)+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()+ return created.agent.id+}+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId+async function turn(client: LocalClient, agentId: string, content: string): Promise<Frame> {+ const started = client.next(isTurn('turn_started', agentId), 45_000, 'turn_started')+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, 'turn_ended')+ client.send('message', { agentId, content })+ const opened = await started+ await ended+ return opened+}++describe('the everyday edges', () => {+ let daemon: IsolatedDaemon | undefined+ afterEach(async () => { await daemon?.close(); daemon = undefined })+ const fresh = async () => {+ const d = await IsolatedDaemon.create()+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-120).join('\n')}`) })+ await d.start()+ return d+ }++ it.each(engines)('%s: folders named with spaces, accents, CJK and quotes', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ for (const folder of ['my project', 'café-déjà vu', '项目 プロジェクト', `it's "quoted"`]) {+ const id = await create(d, client, engine, folder)+ const agent = await bound(client, id)+ // The frame names the folder as its project (agentFrame.ts).+ expect(JSON.stringify(agent.project ?? null), folder).toContain(folder.split(' ')[0])+ await turn(client, id, `hello from ${folder}`)+ }+ client.close()+ })++ it('a folder that is not there is refused, and nothing is left behind', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const missing = await client.request('agent_create', { engine: 'claude', cwd: join(d.projectsDir, 'no', 'such', 'folder'), bypassPermission: true }, 60_000)+ expect(missing.error, JSON.stringify(missing)).toBeTruthy()+ expect((await client.request('agents_list', {})).agents).toEqual([])+ client.close()+ })++ it.each(engines)('%s: a long message and messages that are not plain ASCII arrive whole', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const id = await create(d, client, engine, `text-${engine}`)+ await bound(client, id)+ const long = Array.from({ length: 2_000 }, (_, i) => `line ${i}: the quick brown fox`).join(' ')+ for (const content of [long, 'xin chào — 你好 — こんにちは — مرحبا — 🙂🚀', 'tabs\tand double spaces']) {+ const opened = await turn(client, id, content)+ expect(opened.payload?.userMessage, content.slice(0, 40)).toBe(content)+ }+ client.close()+ })++ it.each(engines)('%s: five messages sent faster than the agent answers are all answered, in order', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const id = await create(d, client, engine, `burst-${engine}`)+ await bound(client, id)+ const asked = ['one', 'two', 'three', 'four', 'five']+ const before = client.frames.length+ for (const content of asked) client.send('message', { agentId: id, content })+ await until('five turns to end', () => client.frames.slice(before).filter(isTurn('turn_ended', id)).length >= asked.length || null, 90_000, 250)+ const started = client.frames.slice(before).filter(isTurn('turn_started', id)).map((frame) => frame.payload?.userMessage)+ expect(started).toEqual(asked)+ client.close()+ })++ it.each(engines)('%s: a fork is its own agent with its own conversation, and the original goes on', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const id = await create(d, client, engine, `fork-${engine}`)+ const original = await bound(client, id)+ await turn(client, id, 'before the fork')+ const forked = await client.request('agent_fork', { agentId: id, name: 'the fork' }, 90_000)+ expect(forked.error, JSON.stringify(forked)).toBeUndefined()+ const forkId: string = forked.agent?.id ?? forked.agentId ?? forked.session?.agentId+ expect(forkId).toBeTruthy()+ expect(forkId).not.toBe(id)+ const fork = await bound(client, forkId)+ expect(fork.sessionId).not.toBe(original.sessionId)+ await turn(client, forkId, 'in the fork')+ await turn(client, id, 'in the original')+ client.close()+ })++ it.each(engines)('%s: a renamed agent keeps its name across a restart', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const id = await create(d, client, engine, `rename-${engine}`)+ await bound(client, id)+ const renamed = await client.request('agent_update', { agentId: id, name: 'Release checklist ✅' }, 30_000)+ expect(renamed.error, JSON.stringify(renamed)).toBeUndefined()+ await until('the new name in the list', async () => (await row(client, id))?.name === 'Release checklist ✅' || null, 15_000, 250)+ await d.restart()+ const again = await LocalClient.connect(d)+ await until('the name after a restart', async () => (await row(again, id))?.name === 'Release checklist ✅' || null, 45_000, 500)+ again.close()+ client.close()+ })+})diff --git a/cli/e2e/robustness.e2e.ts b/cli/e2e/robustness.e2e.tsindex e776fa09c..4d77b19a5 100644--- a/cli/e2e/robustness.e2e.ts+++ b/cli/e2e/robustness.e2e.ts@@ -186,6 +186,33 @@ describe('what the daemon survives', () => {client.close()})+ it('the dial, the window bridges and the device service failing on every call never disconnect the desktop', async () => {+ const d = await fresh({ env: { HARNESSD_TEST_FAULTS: 'dial,window,devices' } })+ await d.start()+ // The handshake itself asks the dial for its status.+ const desktop = await LocalClient.connect(d)+ const agent = await boundAgent(d, desktop, 'devices-failing')+ // What a desktop sends on every pane change, focus, read and spoken reply — each one reaching the dial,+ // a window bridge or the WiFi device service.+ for (let i = 0; i < 3; i++) {+ desktop.send('app_panes', { agentIds: [agent.id], foreground: true })+ desktop.send('app_focus', { agentId: agent.id })+ desktop.send('agent_seen', { agentId: agent.id })+ desktop.send('app_unread', { items: [{ agentId: agent.id, machineId: d.computerId, text: 'done' }] })+ desktop.send('voice_route_reply', { voiceId: 'v1', state: 'taken' })+ desktop.send('dial_settings', { id: 'dial-1', brightness: 3 })+ }+ expect((await desktop.request('agents_list', {}, 15_000)).agents).toHaveLength(1)+ await turn(desktop, agent.id, 'the desktop is still connected')+ expect(desktop.closed).toBe(false)+ expect(d.log()).toContain('[devices] dial failed · injected fault: dial')+ expect(d.log()).toContain('[devices] window failed · injected fault: window')+ expect(d.log()).toContain('[devices] devices failed · injected fault: devices')+ expect(d.log()).not.toContain('local dispatch failed')+ expect(d.coresStarted()).toBe(1)+ desktop.close()+ })+it('state files that are garbage at start: the daemon starts, keeps what it can, and runs a new agent', async () => {const d = await fresh()await d.start()diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 924c62d73..d63cdb1cf 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -138,7 +138,7 @@ import { createTurnActivity } from './core/turns/activity.js'import { createLastTurnReader } from './core/transcripts/lastTurn.js'import { createRecaps } from './core/turns/recaps.js'import { createHeartbeats } from './core/turns/heartbeats.js'-import { createEventFunnel } from './core/turns/funnel.js'+import { createEventFunnel, outsideConsumers } from './core/turns/funnel.js'import { createAgyBackstop } from './core/turns/agyBackstop.js'import { createIngest } from './core/transcripts/ingest.js'import { createTurnHooks } from './core/turns/turnHooks.js'@@ -2843,6 +2843,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {void ensureSignInEpoch().catch(() => null).then(() => devLogSyncer?.register())setInterval(() => { void devLogSyncer?.refresh() }, 10 * 60_000).unref()}+ // The dial, the window bridges and the WiFi device answer for themselves. A throw in any of them is+ // logged — at most once a minute each, with a count of the rest (core/turns/funnel.ts) — and goes no+ // further: the local socket closes a connection whose frame handler throws, so a device fault left+ // unguarded here would disconnect the desktop, again on every pane change.+ const devices = outsideConsumers({ prefix: 'devices', faults: testFaults(process.env.HARNESSD_TEST_FAULTS) })+// Spoken tasks go to the WINDOW to be routed, not to the copy of the router in this process.//// Built here because both ends need it: the local socket hands it the window's replies, and the cable@@ -2875,37 +2881,40 @@ async function runForeground(session: AuthSession | null): Promise<void> {const localWsServer = attachLocalWsServer(hookServer, {localSocketServer: localSocket?.server ?? null,shareRelay,- onSelectionReply: (connId, machineId, payload) => windowSelection.reply(connId, machineId, payload),- onVisitReply: (connId, machineId, payload) => windowVisit.reply(connId, machineId, payload),- onFormReply: (connId, machineId, payload) => windowForm.reply(connId, machineId, payload),+ onSelectionReply: (connId, machineId, payload) => devices('window', () => windowSelection.reply(connId, machineId, payload)),+ onVisitReply: (connId, machineId, payload) => devices('window', () => windowVisit.reply(connId, machineId, payload)),+ onFormReply: (connId, machineId, payload) => devices('window', () => windowForm.reply(connId, machineId, payload)),onAppDisconnect: (machineId, connId) => {if (appFormWindow?.connId === connId) appFormWindow = undefinedif (appVoiceFocus?.connId === connId) appVoiceFocus = undefined- windowForm.disconnected(connId)- windowSelection.focusChanged()- autonomousDeviceService?.appFocus(machineId, null, connId)+ devices('window', () => windowForm.disconnected(connId))+ devices('window', () => windowSelection.focusChanged())+ devices('devices', () => autonomousDeviceService?.appFocus(machineId, null, connId))},// The window and the dial are one desk: opening an agent in the app brings the dial to it, switching// the dial's machine first when the app moved to another one.- onDevicePrepareOpened: (operationId, agentId) => deviceStoreRef?.acknowledgeReveal(operationId, agentId),+ onDevicePrepareOpened: (operationId, agentId) => devices('devices', () => deviceStoreRef?.acknowledgeReveal(operationId, agentId)),onAppFocusState: (machineId, agentId, connId, expectedRevision) => {- // A delayed automatic selection cannot replace a newer explicit user choice.- if (expectedRevision && autonomousDeviceService?.focusSnapshot().focusRevision !== expectedRevision) return false+ // A delayed automatic selection cannot replace a newer explicit user choice. A device service+ // that cannot say which choice is newest is one with no choice to protect: refused, as without one.+ let focusRevision: unknown+ devices('devices', () => { focusRevision = autonomousDeviceService?.focusSnapshot().focusRevision })+ if (expectedRevision && focusRevision !== expectedRevision) return falseappFormWindow = { machineId, connId }if (agentId === null) {if (appVoiceFocus?.connId === connId) appVoiceFocus = undefined} else appVoiceFocus = { machineId, agentId, connId }- windowSelection.focusChanged()- autonomousDeviceService?.appFocus(machineId, agentId, connId)+ devices('window', () => windowSelection.focusChanged())+ devices('devices', () => autonomousDeviceService?.appFocus(machineId, agentId, connId))},- onAppFocus: (machineId, agentId) => { void cableRef?.followApp(machineId, agentId) },+ onAppFocus: (machineId, agentId) => devices('dial', () => { void cableRef?.followApp(machineId, agentId) }),// Everything the window still has unread. Held rather than acted on: the dial is handed it when a// cable attaches, which is the one moment its own drawer is known to be empty.- onAppUnread: (items) => { cableHostRef?.setUnread(items); void cableRef?.replaceNotifications(items) },+ onAppUnread: (items) => devices('dial', () => { cableHostRef?.setUnread(items); void cableRef?.replaceNotifications(items) }),// The window looked at a harness, so the dial's drawer row for it is stale.// The dial's own tap already reaches the window (`agent.open`); this is the// return leg, and the pair is what keeps the badge and the pill equal.- onAgentSeen: (agentId, readToken) => { void cableRef?.agentSeen(agentId, readToken) },+ onAgentSeen: (agentId, readToken) => devices('dial', () => { void cableRef?.agentSeen(agentId, readToken) }),// Agents the window has a tile for. A finished turn on one of these is// already in front of the person, so the dial updates its tile in silence// rather than beeping about something being looked at.@@ -2918,9 +2927,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// window with an empty swarm is an empty carousel, not the whole machine.onAppSwarms: (swarms) => {appSwarmsLatest = swarms- cableHostRef?.setSwarms(swarms)- void cableRef?.syncSwarms()- void cableRef?.syncAgents()+ devices('dial', () => {+ cableHostRef?.setSwarms(swarms)+ void cableRef?.syncSwarms()+ void cableRef?.syncAgents()+ })},onAppTabAgents: (connection, ids) => cleanupTabs.updateWindow(connection, ids),onAppPanes: (agentIds, foreground) => {@@ -2944,7 +2955,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// below is what `quiet` is read from, so emptying it is how both screens// come to the same answer.appWindowForeground = foreground- cableHostRef?.setDesk(agentIds)+ devices('dial', () => cableHostRef?.setDesk(agentIds))const next = new Set(agentIds)// Logged on CHANGE only. It fires on every pane add, close and reconnect,// and it is the one place the whole feature is observable from — without@@ -2953,7 +2964,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {openPaneAgents = nextif (changed) console.log(`[cable] window tiles: ${next.size ? [...next].map(sid).join(' ') : '(none)'}`)// Ordered, not set-wise: two tiles swapping places is the same set and a different ring.- if (deskChanged) void cableRef?.syncAgents()+ if (deskChanged) devices('dial', () => { void cableRef?.syncAgents() })},// ⌘K in the window: a typed task, and which agent it belongs to.//@@ -3092,7 +3103,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// difference (local → the same door the web and the hooks use, remote → the fleet), and it is the// one the dial has been using for every voice turn.// A window that connects after the dial did has missed the `dial_status` that announced it.- dialStatus: () => cableHostRef?.currentDialStatus() ?? { attached: false },+ dialStatus: () => {+ let status: ReturnType<DaemonCableHost['currentDialStatus']> | undefined+ devices('dial', () => { status = cableHostRef?.currentDialStatus() })+ return status ?? { attached: false }+ },/** A window changing a device's settings. Addressed by the fleet's id, so a second robot on the same* desk is not dragged along — every other cable command broadcasts on purpose (they all show the@@ -3101,12 +3116,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {* Nothing is answered here. The device replies to its own `settings.set` with the values it now* holds, and that reaches the window as an ordinary `dial_status`.*/- onDialSettings: (id, patch) => {+ onDialSettings: (id, patch) => devices('dial', () => {void cableRef?.setSettings(id, patch as Parameters<NonNullable<typeof cableRef>['setSettings']>[1]).then(result => {if (!result.ok) console.log(`[cable] settings for ${id || 'no device'}: ${result.error}`)})- },+ }),openQuestions: () => [...openQuestions.values()],onRouteSend: backend.ownerCommands.onRouteSend = (agentId, text) => {const sent = cableHostRef?.sendTurn(agentId, text) ?? { ok: false as const, machine: '', reason: 'no agent list yet' }@@ -3114,7 +3129,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {+ (sent.ok ? '' : ` · REFUSED: ${sent.reason}${sent.machine ? ` (${sent.machine})` : ''}`))return sent},- onVoiceRouteReply: (voiceId, reply) => windowRouter.reply(voiceId, reply),+ onVoiceRouteReply: (voiceId, reply) => devices('window', () => windowRouter.reply(voiceId, reply)),machineId: backend.machineId,backend,relayPool,@@ -4036,7 +4051,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Every card bound for the WiFi device goes down the cable too, translated once. Teeing beats emitting// again at each call site: a new event kind reaches the dial the day it reaches the socket.- backend.onOutboundCommander = (frame) => {+ // The tee runs before the frame is queued for the WiFi device (BackendSocket.sendCommander): a dial+ // fault here must cost neither that frame nor whoever is sending it.+ backend.onOutboundCommander = (frame) => devices('dial', () => {autonomousDeviceService?.commander(frame as Record<string, unknown>)// THIS COMPUTER'S cards, by definition — and every one of them belongs to a tile that is on the// carousel, because the carousel now spans machines. The old guard dropped them whenever the wheel@@ -4064,7 +4081,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {void cable.summary(event.agentId, event.recap || event.text, event.text, alreadyOnScreen(event.agentId), event.subagent)}else void cable.turnError(event.agentId, event.text)- }+ })// A remote machine's cards reach the dial through the SAME four calls the local tee uses, so a new// event kind lands on both surfaces the day it lands on either.diff --git a/cli/src/core/turns/funnel.spec.ts b/cli/src/core/turns/funnel.spec.tsindex 3ccfd7b23..a33e2c5a8 100644--- a/cli/src/core/turns/funnel.spec.ts+++ b/cli/src/core/turns/funnel.spec.ts@@ -213,7 +213,7 @@ describe('a consumer outside the core', () => {it('is logged at most once a minute, with how many failures went unsaid, and never stops the caller', () => {const lines: string[] = []let at = 0- const outside = outsideConsumers((line) => lines.push(line), () => at)+ const outside = outsideConsumers({ log: (line) => lines.push(line), now: () => at })const ran: string[] = []outside('devices', () => { throw new Error('serial port gone') })at += 10_000@@ -237,4 +237,14 @@ describe('a consumer outside the core', () => {expect(error).toHaveBeenCalledWith('[funnel] teams failed · x')error.mockRestore()})++ it('says whose it is, and fails a consumer named in the end-to-end suite\'s faults without running it', () => {+ const lines: string[] = []+ const ran: string[] = []+ const outside = outsideConsumers({ log: (line) => lines.push(line), prefix: 'devices', faults: new Set(['dial']) })+ outside('dial', () => { ran.push('dial') })+ outside('window', () => { ran.push('window') })+ expect(ran).toEqual(['window'])+ expect(lines).toEqual(['[devices] dial failed · injected fault: dial'])+ })})diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.tsindex b5e5761d1..09868a747 100644--- a/cli/src/core/turns/funnel.ts+++ b/cli/src/core/turns/funnel.ts@@ -63,16 +63,29 @@ type OutsideConsumers = (consumer: string, call: () => void) => void* throws is logged, at most once a minute per consumer and with how many were not, and every consumer* after it still gets the event. The heartbeat, the question watcher and the recaps must not miss a* turn because a device was unplugged mid-call. The services on the boundary are guarded the same way- * (core/serviceHost.ts).+ * (core/serviceHost.ts), and so are the dial and the window bridges on the local socket (cli.ts).*/-export function outsideConsumers(log: (line: string) => void = (line) => console.error(line), now: () => number = Date.now): OutsideConsumers {+export function outsideConsumers(options: {+ log?: (line: string) => void+ now?: () => number+ /** What the lines start with: `[funnel]` by default. */+ prefix?: string+ /** Consumers to fail on every call, for the end-to-end suite only (`HARNESSD_TEST_FAULTS`). */+ faults?: ReadonlySet<string>+} = {}): OutsideConsumers {+ const log = options.log ?? ((line: string) => console.error(line))+ const now = options.now ?? Date.now+ const prefix = options.prefix ?? 'funnel'const said = new Map<string, { at: number; quiet: number }>()return (consumer, call) => {- try { call() } catch (error) {+ try {+ if (options.faults?.has(consumer)) throw new Error(`injected fault: ${consumer}`)+ call()+ } catch (error) {const at = now()const last = said.get(consumer)if (last && at - last.at < 60_000) { last.quiet++; return }- log(`[funnel] ${consumer} failed · ${error instanceof Error ? error.message : String(error)}${last?.quiet ? ` · ${last.quiet} more since` : ''}`)+ log(`[${prefix}] ${consumer} failed · ${error instanceof Error ? error.message : String(error)}${last?.quiet ? ` · ${last.quiet} more since` : ''}`)said.set(consumer, { at, quiet: 0 })}}diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex 181d9ca4a..e6fd50b3d 100644--- a/cli/src/lib/sessionInput.spec.ts+++ b/cli/src/lib/sessionInput.spec.ts@@ -819,9 +819,11 @@ describe('delivery correlation', () => {describe('optional lamp delivery preserves legacy behavior', () => {afterEach(() => vi.useRealTimers())- it('keeps concurrent untracked Claude submits out of the new lamp queue', async () => {+ it('keeps untracked Claude submits out of the new lamp queue, writing them one after another', async () => {+ // Not held for the turn — Claude takes typing while it works — but never two writes into the pane at+ // once: the second waits for the first's paste, not for the first's turn.const validations: Array<(valid: boolean) => void> = []- const inject = vi.fn(async () => true)+ const inject = vi.fn(async (_target: string, _text: string) => true)const controller = new SessionInputController({getSession: () => session('claude'),validateRuntime: () => new Promise<boolean>(resolve => validations.push(resolve)),@@ -830,12 +832,42 @@ describe('optional lamp delivery preserves legacy behavior', () => {controller.setTurnOpen('s1', true)controller.submit('s1', 'first local prompt')controller.submit('s1', 'second local prompt')- expect(validations).toHaveLength(2)- validations.forEach(resolve => resolve(true))+ expect(validations).toHaveLength(1)+ validations[0](true)+ await vi.waitFor(() => expect(validations).toHaveLength(2))+ expect(inject.mock.calls.map(([, text]) => text)).toEqual(['first local prompt'])+ validations[1](true)await vi.waitFor(() => expect(inject).toHaveBeenCalledTimes(2))+ expect(inject.mock.calls.map(([, text]) => text)).toEqual(['first local prompt', 'second local prompt'])controller.forget('s1')})+ it('writes messages that arrive together in the order they arrived, whichever check finishes first', async () => {+ const checks: Array<(valid: boolean) => void> = []+ const inject = vi.fn(async (_target: string, _text: string) => true)+ const controller = new SessionInputController({+ getSession: () => session('codex'),+ validateRuntime: () => new Promise<boolean>(resolve => checks.push(resolve)),+ inject, sendKey: async () => true, onError: vi.fn(),+ })+ for (const text of ['one', 'two', 'three']) controller.submit('s1', text)+ for (let i = 0; i < 3; i++) {+ await vi.waitFor(() => expect(checks.length).toBe(i + 1))+ checks[i](true)+ }+ await vi.waitFor(() => expect(inject).toHaveBeenCalledTimes(3))+ expect(inject.mock.calls.map(([, text]) => text)).toEqual(['one', 'two', 'three'])+ // A write that fails does not hold up the ones behind it.+ const failing = vi.fn(async (_target: string, text: string) => { if (text === 'bad') throw new Error('pane gone'); return true })+ const next = new SessionInputController({ getSession: () => session('codex'), validateRuntime: async () => true,+ inject: failing, sendKey: async () => true, onError: vi.fn() })+ next.submit('s1', 'bad')+ next.submit('s1', 'good')+ await vi.waitFor(() => expect(failing).toHaveBeenCalledTimes(2))+ controller.forget('s1')+ next.forget('s1')+ })+it('keeps native control available during untracked runtime validation', async () => {let resolve!: (valid: boolean) => voidconst controller = new SessionInputController({diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex 23a967c31..231f4696a 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -82,6 +82,8 @@ interface QueuedInput {}interface InputState {+ /** The writes this agent's messages are making, one after another in the order they arrived. */+ writes?: Promise<void>deliveryId?: stringdeliveryFingerprint?: stringdispatching?: boolean@@ -243,7 +245,18 @@ export class SessionInputController {return}this.delivery(sessionId, deliveryId, 'queued')- void this.inject(sessionId, session, content, deliveryId, tabId)+ // One write at a time per agent, in the order the messages arrived. Claude Code and Codex take+ // typing while a turn runs, so a message is not held for the turn — but two pastes into one pane at+ // once interleave: one message's text lands between another's paste and its Enter, and the engine+ // receives a single prompt made of both. Found end to end: five messages sent within 30 ms became+ // two turns, "one" and "three" run together and the rest, out of order. Each write starts with the+ // agent as it is by then, which a restart in between may have changed.+ // With nothing in flight the write starts at once, so a cancel or a control request that follows+ // the submit sees it, as before.+ const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId, tabId)+ const running = state.writes ? state.writes.then(write, write) : write()+ const settled: Promise<void> = running.catch(() => {}).then(() => { if (state.writes === settled) state.writes = undefined })+ state.writes = settled}/** Reserve this pane for a short native control interaction such as `/model`. */diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex 16bf61b60..b5e962d2b 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -533,6 +533,16 @@ Found while mapping, and fixed on their own rather than inside a move:- Kept as it is, on purpose: a transcript deleted and recreated at the same path is read as arewrite, so the first burst in the new file is history and every turn after it is live. Readinga shrunken file as new content once replayed a rewrite as fresh turns (42 in one second).+ - Part 12: the local socket closes a connection whose frame handler throws, and its window+ handlers called the dial, the window bridges and the WiFi device service in line, so a fault in+ any of them disconnected the desktop, again on every pane change. Every such call, and the+ commander tee that runs before a frame is queued for the WiFi device, is guarded now; with all+ three failing on every call the desktop stays connected and its agents run their turns.+ - Part 12, found by the third round (`e2e/edges.e2e.ts`): messages sent faster than an agent+ answers were written into its pane at the same time, so their pastes interleaved and the engine+ received prompts made of two messages, out of order (five messages became two turns). Each+ agent's messages are now written one after another, in the order they arrived; they still never+ wait for a turn.## Testing