Skip to content

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.

fix(cli): lower terminal input latency

tonya56f961e6a01
diff --git a/cli/e2e/phoneTyping.e2e.ts b/cli/e2e/phoneTyping.e2e.ts
new file mode 100644
index 000000000..9b0b127d5
--- /dev/null
+++ b/cli/e2e/phoneTyping.e2e.ts
@@ -0,0 +1,93 @@
+/**
+ * PHONE_TYPING=1: a phone's keystroke → echo over its P2P channel, idle and while another pane on the same
+ * connection is taking a keyframe. PHONE_TYPING_REPORT=<file> writes JSON; PHONE_TYPING_N=<keys> (default 60).
+ *
+ * Why it exists: a remote client's keystrokes waited in its connection's line behind every request it made —
+ * another pane's resize keyframe (Codex: ~200ms at the median, it waits for its repaint), an `agents_list`, a
+ * `session_get` — while a window on this computer never did (backendSocket.ts `enqueueTerminalBinary`). The
+ * desktop's typing is measured by typingLatency.e2e.ts; this is the phone's. Run alone: the host's load is the noise.
+ */
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join, resolve } from 'node:path'
+import { it } from 'vitest'
+import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'
+import { LocalClient } from './harness/client.js'
+import { CLI_ROOT, until } from './harness/daemon.js'
+import { startPhoneMachine } from './harness/fleet.js'
+import { P2pPhone } from './harness/p2pPhone.js'
+
+const N = Number(process.env.PHONE_TYPING_N ?? 60)
+const sleep = (ms: number) => new Promise<void>((done) => setTimeout(done, ms))
+const key = (i: number) => (i % 2 === 0 ? 'x' : '\x7f')
+
+function stats(values: number[]) {
+ const sorted = [...values].sort((a, b) => a - b)
+ const at = (p: number) => +sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))].toFixed(1)
+ return { n: sorted.length, p50: at(0.5), p90: at(0.9), max: +sorted[sorted.length - 1].toFixed(1) }
+}
+
+it.runIf(process.env.PHONE_TYPING === '1')('a phone\'s typing latency over P2P, idle and beside another pane\'s keyframe', async () => {
+ const world = await startPhoneMachine()
+ const { machine } = world
+ let desk: LocalClient | undefined
+ let phone: P2pPhone | undefined
+ const alive: NodeJS.Timeout[] = []
+ try {
+ desk = await LocalClient.connect(machine.daemon, { machineId: machine.machineId })
+ const create = async (engine: 'claude' | 'codex', folder: string) => {
+ const cwd = join(machine.daemon.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await desk!.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ if (created.error) throw new Error(JSON.stringify(created))
+ return until(`${folder} active`, async () => {
+ const rows = (await desk!.request('agents_list', { includeStopped: true }, 30_000)).agents as Array<Record<string, any>>
+ return rows.find((row) => row.id === created.agent.id && row.sessionId && row.status === 'active') ?? null
+ }, 60_000, 500)
+ }
+ const target = await create('claude', 'typed-into')
+ const beside = await create('codex', 'beside')
+ phone = await P2pPhone.open(world)
+ await phone.negotiate()
+ const open = async (agentId: string, rows: number) => {
+ const requestId = `open-${Math.random().toString(36).slice(2)}`
+ phone!.send('terminal_open', { requestId, protocolVersion: 3, agentId, cols: 100, rows }, 'p2p')
+ const ready = await until('terminal_ready', () => phone!.frames.find(({ frame }) => frame.type === 'terminal_ready' && frame.payload?.requestId === requestId), 30_000)
+ const streamId = ready.frame.payload!.streamId as string
+ await until('the opening keyframe', () => phone!.binaries.find(({ frame }) => frame.streamId === streamId && frame.kind === TerminalBinaryKind.keyframe), 30_000)
+ return streamId
+ }
+ const typed = await open(target.id, 30)
+ const other = await open(beside.id, 30)
+ alive.push(setInterval(() => { for (const streamId of [typed, other]) phone!.send('terminal_alive', { streamId }, 'p2p') }, 5_000))
+ await sleep(2_000)
+
+ let seq = 0
+ let resizeSeq = 0
+ const measure = async (besideKeyframe: boolean) => {
+ const out: number[] = []
+ for (let i = 0; i < N; i++) {
+ if (besideKeyframe) phone!.send('terminal_resize', { streamId: other, resizeSeq: resizeSeq++, cols: 100, rows: i % 2 === 0 ? 24 : 30 }, 'p2p')
+ const since = phone!.binaries.length
+ const started = performance.now()
+ phone!.sendBinary({ kind: TerminalBinaryKind.input, streamId: typed, seq: seq++, compressed: false, bytes: Buffer.from(key(i)) })
+ const echo = await until('the echo', () => phone!.binaries.slice(since).find(({ frame }) => frame.streamId === typed && frame.kind === TerminalBinaryKind.output), 10_000, 1)
+ out.push(performance.now() - started)
+ phone!.send('terminal_ack', { streamId: typed, lastSeq: echo.frame.seq }, 'p2p')
+ const last = phone!.binaries.filter(({ frame }) => frame.streamId === other).at(-1)
+ if (last) phone!.send('terminal_ack', { streamId: other, lastSeq: last.frame.seq }, 'p2p')
+ await sleep(besideKeyframe ? 450 : 25)
+ }
+ return stats(out)
+ }
+ const idle = await measure(false)
+ const besideKeyframe = await measure(true)
+ const report = { schema: 1, at: new Date().toISOString(), keys: N, idle, besideKeyframe, errors: phone.errors }
+ console.log(`phone typing latency: ${JSON.stringify(report)}`)
+ if (process.env.PHONE_TYPING_REPORT) writeFileSync(resolve(CLI_ROOT, process.env.PHONE_TYPING_REPORT), `${JSON.stringify(report, null, 2)}\n`)
+ } finally {
+ for (const timer of alive) clearInterval(timer)
+ await phone?.close().catch(() => {})
+ desk?.close()
+ await world.close()
+ }
+}, 600_000)
diff --git a/cli/src/backendSocket.lanes.spec.ts b/cli/src/backendSocket.lanes.spec.ts
new file mode 100644
index 000000000..cfd7ef946
--- /dev/null
+++ b/cli/src/backendSocket.lanes.spec.ts
@@ -0,0 +1,192 @@
+/**
+ * The order a remote client's terminal frames are handled in. Its keystrokes used to wait in its
+ * connection's line behind every request it made — an `agents_list`, a `session_get`, its own pane's
+ * resize keyframe on each keyboard show or hide — and a phone typed into a pane that answered seconds
+ * late. These hold the rules that replaced it: a stream's bytes keep their own order and nothing else's,
+ * an upload's control frames stay in line with its chunks, and a stream's bookkeeping is never queued.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
+import { TerminalBinaryKind, type TerminalBinaryClear } from './lib/terminalBinary.js'
+import { env } from './config/env.js'
+import { relaySocket } from './testing/relaySocket.js'
+
+afterEach(() => vi.restoreAllMocks())
+
+const STREAM_A = '00000000-0000-4000-8000-00000000000a'
+const STREAM_B = '00000000-0000-4000-8000-00000000000b'
+
+const kindName = (kind: TerminalBinaryKind): string =>
+ kind === TerminalBinaryKind.input ? 'input' : kind === TerminalBinaryKind.paste ? 'paste' : kind === TerminalBinaryKind.imagePaste ? 'imagePaste' : String(kind)
+
+const input = (streamId: string, seq: number, kind = TerminalBinaryKind.input): TerminalBinaryClear =>
+ ({ kind, streamId, seq, bytes: new TextEncoder().encode(String(seq)), compressed: false })
+
+/** A promise the test settles, and whether anything has waited on it. */
+function gate() {
+ let open!: () => void
+ const opened = new Promise<void>((resolve) => { open = resolve })
+ return { opened, open }
+}
+
+/** A socket whose terminal streams record what reached them, and hold whatever the test tells them to. */
+function streamsOn() {
+ const socket = relaySocket('fixture')
+ const seen: string[] = []
+ const holds = new Map<string, Promise<void>>()
+ const hold = (what: string) => { const g = gate(); holds.set(what, g.opened); return g.open }
+ const handleFrame = vi.fn(async (_connId: string, type: string, payload: Record<string, unknown>) => {
+ const what = `${type}:${String(payload.streamId ?? '')}`
+ seen.push(what)
+ await holds.get(what)
+ return true
+ })
+ const handleBinary = vi.fn(async (_connId: string, frame: TerminalBinaryClear) => {
+ const what = `${kindName(frame.kind)}:${frame.streamId}:${frame.seq}`
+ seen.push(what)
+ await holds.get(what)
+ })
+ socket.setTerminalStreamManager({
+ handleFrame, handleBinary,
+ closeConnection: vi.fn(async () => {}), closeConnectionsWhere: vi.fn(async () => {}), stop: vi.fn(async () => {}),
+ } as unknown as TerminalStreamManager)
+ const frame = (type: string, payload: Record<string, unknown>) =>
+ socket.fromGateway.frame('phone-1', { type, payload }, 'relay', 'web')
+ const binary = (clear: TerminalBinaryClear) => socket.fromGateway.binary('phone-1', clear)
+ return { socket, seen, hold, frame, binary }
+}
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
+
+describe('a remote client\'s keystrokes', () => {
+ it('reach their pane while its resize keyframe is still being taken', async () => {
+ const { socket, seen, hold, frame, binary } = streamsOn()
+ const keyframeDone = hold(`terminal_resize:${STREAM_A}`)
+ void frame('terminal_resize', { streamId: STREAM_A, resizeSeq: 1, cols: 42, rows: 24 })
+ await settle()
+ void binary(input(STREAM_A, 1))
+ await settle()
+ expect(seen).toEqual([`terminal_resize:${STREAM_A}`, `input:${STREAM_A}:1`])
+ keyframeDone()
+ await socket.stop()
+ })
+
+ it('reach their pane while a slow request on the same connection is still being answered', async () => {
+ const { socket, seen, frame, binary } = streamsOn()
+ const history = gate()
+ ;(socket as unknown as { historyProvider: () => Promise<Record<string, unknown>> }).historyProvider = async () => { await history.opened; return {} }
+ void frame('session_get', { requestId: 'h-1', agentId: 'a1' })
+ void binary(input(STREAM_A, 1))
+ await settle()
+ expect(seen).toEqual([`input:${STREAM_A}:1`])
+ history.open()
+ await socket.stop()
+ })
+
+ it('keep their own stream\'s order: a key typed after a paste waits for the paste, another pane\'s does not', async () => {
+ const { socket, seen, hold, binary } = streamsOn()
+ const pasted = hold(`paste:${STREAM_A}:0`)
+ void binary(input(STREAM_A, 0, TerminalBinaryKind.paste))
+ void binary(input(STREAM_A, 1))
+ void binary(input(STREAM_B, 1))
+ await settle()
+ expect(seen).toEqual([`paste:${STREAM_A}:0`, `input:${STREAM_B}:1`])
+ pasted()
+ await vi.waitFor(() => expect(seen).toEqual([`paste:${STREAM_A}:0`, `input:${STREAM_B}:1`, `input:${STREAM_A}:1`]))
+ await socket.stop()
+ })
+
+ it('go on after one of them fails', async () => {
+ const { socket, seen, binary } = streamsOn()
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const streams = (socket as unknown as { terminalStreams: { handleBinary: ReturnType<typeof vi.fn> } }).terminalStreams
+ streams.handleBinary.mockImplementationOnce(async () => { throw new Error('tmux went away') })
+ void binary(input(STREAM_A, 1))
+ await binary(input(STREAM_A, 2))
+ expect(seen).toEqual([`input:${STREAM_A}:2`])
+ expect(error).toHaveBeenCalledWith('[backend] binary terminal dispatch failed:', 'tmux went away')
+ await socket.stop()
+ })
+})
+
+describe('a remote client\'s keystrokes, traced', () => {
+ it('say how long each waited in its stream\'s line while tracing is on, and nothing while it is off', async () => {
+ const { socket, hold, binary } = streamsOn()
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const traced = () => log.mock.calls.map((call) => String(call[0])).filter((line) => line.startsWith('[typing]'))
+ await binary(input(STREAM_A, 0))
+ expect(traced()).toEqual([])
+ const was = env.TYPING_TRACE
+ ;(env as { TYPING_TRACE: boolean }).TYPING_TRACE = true
+ try {
+ const pasted = hold(`paste:${STREAM_A}:0`)
+ void binary(input(STREAM_A, 0, TerminalBinaryKind.paste))
+ const typed = binary(input(STREAM_A, 1))
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ pasted()
+ await typed
+ expect(traced()).toEqual([expect.stringMatching(new RegExp(`^\\[typing\\] lane conn=phone-1 stream=${STREAM_A.slice(0, 8)} seq=1 waited (1\\d|[2-9]\\d|\\d{3,})ms$`))])
+ } finally {
+ ;(env as { TYPING_TRACE: boolean }).TYPING_TRACE = was
+ await socket.stop()
+ }
+ })
+})
+
+describe('a stream\'s acknowledgements and heartbeats', () => {
+ it('are handled while the connection waits on a request', async () => {
+ // An ack stuck behind a slow request let unacknowledged output reach the pause mark: the screen stopped.
+ const { socket, seen, hold, frame } = streamsOn()
+ const keyframeDone = hold(`terminal_resize:${STREAM_A}`)
+ void frame('terminal_resize', { streamId: STREAM_A, resizeSeq: 1, cols: 42, rows: 24 })
+ await settle()
+ void frame('terminal_ack', { streamId: STREAM_A, lastSeq: 3 })
+ void frame('terminal_alive', { streamId: STREAM_A })
+ await settle()
+ expect(seen).toEqual([`terminal_resize:${STREAM_A}`, `terminal_ack:${STREAM_A}`, `terminal_alive:${STREAM_A}`])
+ keyframeDone()
+ await socket.stop()
+ })
+
+ it('wait at the gate like everything else while the daemon is starting', async () => {
+ const { socket, seen, frame } = streamsOn()
+ socket.holdRequests()
+ void frame('terminal_ack', { streamId: STREAM_A, lastSeq: 3 })
+ await settle()
+ expect(seen).toEqual([])
+ socket.openRequests()
+ await vi.waitFor(() => expect(seen).toEqual([`terminal_ack:${STREAM_A}`]))
+ await socket.stop()
+ })
+})
+
+describe('an upload\'s begin and cancel', () => {
+ it('stay in line with the chunks already waiting in their stream', async () => {
+ // A cancel and a new begin let past the old upload's chunks took those chunks into the new upload.
+ const { socket, seen, hold, frame, binary } = streamsOn()
+ const chunkDone = hold(`imagePaste:${STREAM_A}:0`)
+ void binary(input(STREAM_A, 0, TerminalBinaryKind.imagePaste))
+ void binary(input(STREAM_A, 1, TerminalBinaryKind.imagePaste))
+ void frame('terminal_chunked_upload_cancel', { streamId: STREAM_A })
+ void frame('terminal_chunked_upload_begin', { streamId: STREAM_A, requestId: 'u-2' })
+ await settle()
+ expect(seen).toEqual([`imagePaste:${STREAM_A}:0`])
+ chunkDone()
+ await vi.waitFor(() => expect(seen).toEqual([
+ `imagePaste:${STREAM_A}:0`,
+ `imagePaste:${STREAM_A}:1`,
+ `terminal_chunked_upload_cancel:${STREAM_A}`,
+ `terminal_chunked_upload_begin:${STREAM_A}`,
+ ]))
+ await socket.stop()
+ })
+
+ it('from a window on this computer keep the window\'s own line, which its bytes never waited in', async () => {
+ const { socket, seen } = streamsOn()
+ socket.registerLocalClient('local:window', { sendFrame: () => true, sendBinary: () => true })
+ socket.handleLocalFrame('local:window', { type: 'terminal_chunked_upload_begin', payload: { streamId: STREAM_A, requestId: 'u-1' } })
+ await vi.waitFor(() => expect(seen).toEqual([`terminal_chunked_upload_begin:${STREAM_A}`]))
+ await socket.unregisterLocalClient('local:window')
+ await socket.stop()
+ })
+})
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 4cd91a154..c8b262422 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -183,8 +183,8 @@ describe('reviewed permanent deletion RPCs', () => {
const { sealTerminalBinary } = await import('./lib/e2ee/terminalSeal.js')
const raw = sealTerminalBinary(new Uint8Array(32).fill(7), 9, { kind: 1, streamId: '00112233-4455-6677-8899-aabbccddeeff', seq: 1, bytes: new TextEncoder().encode('ls\r'), compressed: false })!
const gateway = gatewayOf(socket) as any
+ // Opened as it arrives, outside the connection's line: told at once.
gateway.enqueueTerminalBinary('web:gone', raw)
- await gateway.downChains.get('web:gone')
expect(upstreamOf(socket).queue.map((item: { msg: unknown }) => item.msg)).toContainEqual({ t: 'up', targetConnId: 'web:gone', frame: { type: 'e2e_session_unknown', payload: { refused: { type: 'terminal_binary', kind: 1, n: 9 } } } })
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 4ef61245a..9bd7c5eb1 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -41,7 +41,7 @@ import { terminalHandoffRequest } from './lib/terminalHandoff.js'
import { OwnerCommands, ROUTE_COMMAND_TYPES } from './lib/ownerCommands.js'
import { VIEWER_DOWN_TYPES } from './lib/viewerFrames.js'
import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
-import { encodeTerminalLocal, type TerminalBinaryClear } from './lib/terminalBinary.js'
+import { encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from './lib/terminalBinary.js'
import { BACKEND_ONLY_DOWN_TYPES, GATEWAY_REQUEST_TYPES, isLocalClientId, logSafeType, PAIR_REQUESTS, PLATE_REQUEST, rpcResultType, type DownTransport } from './lib/relayFrames.js'
import { sid, logFrame } from './lib/log.js'
import { eventAgentId, GUEST_REFUSALS, guestVerdict } from './core/guestPolicy.js'
@@ -51,6 +51,10 @@ export { isLocalClientId, type DownTransport }
/** Requests one local connection may queue before the daemon is ready (see `openRequests`). The app
* sends a handful on connect; hundreds is a client looping, not a person. */
const MAX_REQUESTS_BEFORE_READY = 256
+/** A terminal stream's bookkeeping, handled as it arrives rather than in its connection's line — see `enqueueDown`. */
+const TERMINAL_BOOKKEEPING_TYPES: ReadonlySet<string> = new Set(['terminal_ack', 'terminal_alive'])
+/** An upload's control frames, which go in line with its chunks — see `enqueueDown`. */
+const TERMINAL_UPLOAD_CONTROL_TYPES: ReadonlySet<string> = new Set(['terminal_chunked_upload_begin', 'terminal_chunked_upload_cancel'])
/** Agent Messages' requests, which the frame log leaves out: they carry what agents say to each other. */
const MESSAGE_REQUESTS: ReadonlySet<string> = new Set(MESSAGES_REQUESTS)
/** Share's requests, which the frame log leaves out as well: they carry who a harness is shared with. */
@@ -77,6 +81,8 @@ export class BackendSocket {
/** Whether the backend link is up, as the gateway last said. */
private linkUp = false
private readonly downChains = new Map<string, Promise<void>>()
+ /** A remote client's terminal bytes, per connection and stream — see `enqueueTerminalBinary`. */
+ private readonly streamLanes = new Map<string, Promise<void>>()
/**
* Requests wait here until the daemon is ready (`openRequests`), each in its connection's own order.
* The port answers long before start-up has wired every handler and confirmed the agents it
@@ -752,6 +758,23 @@ export class BackendSocket {
return Promise.resolve()
}
}
+ const type = frame.type
+ // A stream's acknowledgements and heartbeats are bookkeeping that every other frame may be ordered
+ // around (an ack for output a keyframe has since replaced is ignored), and one stuck behind a slow
+ // request let unacknowledged output pile up to the pause mark (384 KiB): the screen stopped while the
+ // connection waited on, say, `agents_list`.
+ if (this.requestsOpen && typeof type === 'string' && TERMINAL_BOOKKEEPING_TYPES.has(type)) {
+ return this.dispatchDown(frame, connId, transport, role).catch((err) => {
+ console.error('[backend] down-frame dispatch failed:', err instanceof Error ? err.message : err)
+ })
+ }
+ // An upload's begin and cancel go in line with its chunks, which ride the stream's input lane: a cancel
+ // and a new begin let through while the old upload's chunks still waited there would have taken those
+ // chunks into the new upload.
+ const streamId = (frame.payload as { streamId?: unknown } | undefined)?.streamId
+ if (transport !== 'local' && typeof type === 'string' && TERMINAL_UPLOAD_CONTROL_TYPES.has(type) && typeof streamId === 'string') {
+ return this.inStreamLane(connId, streamId, () => this.dispatchDown(frame, connId, transport, role), 'down-frame')
+ }
const previous = this.downChains.get(key) ?? Promise.resolve()
const next = previous
.catch(() => { /* prior failure is already logged */ })
@@ -767,21 +790,39 @@ export class BackendSocket {
return next
}
- /** A remote client's terminal bytes, opened by the gateway, in its connection's order (not gated: a
- * stream exists only once a request through the gate opened it). */
+ /**
+ * A remote client's terminal bytes, opened by the gateway: in their stream's order, and in nothing else's
+ * (not gated: a stream exists only once a request through the gate opened it). They used to share the
+ * connection's line with its requests, so a keystroke waited for whatever came before it: an
+ * `agents_list` (1–2s with ~250 agents), a `session_get` (up to 5s for a cold engine reader), another
+ * pane's keyframe (Codex: ~200ms and ~166KB at the median, daemon log 2026-10-13..15). Its own pane's
+ * keyframe still holds the echo, as it holds all of that pane's output, but no longer the keystroke. A
+ * window on this computer never waited (its bytes go straight to the streams, `handleLocalBinary`); a
+ * phone now does not either. A paste still holds the keystrokes typed after it, and an upload's chunks
+ * stay in line with its begin and cancel.
+ */
private enqueueTerminalBinary(connId: string, clear: TerminalBinaryClear): Promise<void> {
- const key = connId || '__backend__'
- const previous = this.downChains.get(key) ?? Promise.resolve()
+ const traced = env.TYPING_TRACE && clear.kind === TerminalBinaryKind.input
+ const queuedAt = traced ? performance.now() : 0
+ return this.inStreamLane(connId, clear.streamId, async () => {
+ if (traced) console.log(`[typing] lane conn=${sid(connId)} stream=${sid(clear.streamId)} seq=${clear.seq} waited ${Math.round(performance.now() - queuedAt)}ms`)
+ await this.terminalStreams?.handleBinary(connId, clear)
+ }, 'binary terminal')
+ }
+
+ private inStreamLane(connId: string, streamId: string, task: () => Promise<void>, what: string): Promise<void> {
+ const key = `${connId || '__backend__'}\0${streamId}`
+ const previous = this.streamLanes.get(key) ?? Promise.resolve()
const next = previous
.catch(() => { /* prior failure is already logged */ })
- .then(async () => { await this.terminalStreams?.handleBinary(connId, clear) })
+ .then(task)
.catch((err) => {
- console.error('[backend] binary terminal dispatch failed:', err instanceof Error ? err.message : err)
+ console.error(`[backend] ${what} dispatch failed:`, err instanceof Error ? err.message : err)
})
.finally(() => {
- if (this.downChains.get(key) === next) this.downChains.delete(key)
+ if (this.streamLanes.get(key) === next) this.streamLanes.delete(key)
})
- this.downChains.set(key, next)
+ this.streamLanes.set(key, next)
return next
}
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index b228a3e36..3b23f50f1 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -313,6 +313,11 @@ const fields = {
// encrypted on the wire, so a packet capture cannot answer "what did the adapter actually send".
// Never prints message text, transcripts, tokens or payload bodies.
LOG_FRAMES: flag('false'),
+ // Log a remote client's keystrokes on their way to the pane and back: which wire each came on, how long it
+ // waited in line, held for a missing one, and until its echo went out. OFF by default: one line per hop per
+ // keystroke. Numbers and timings only (stream, seq, size) — never what was typed. The phone's own half is
+ // `--dart-define=HARNESS_TYPING_TRACE=true` (mobile/lib/logging/typing_trace.dart).
+ TYPING_TRACE: flag('false'),
// TEMPORARY / diagnostic. Forces iceTransportPolicy:'relay', so the ONLY candidate either peer can
// offer is a Cloudflare TURN allocation — the way to exercise the relay path on a pair that would
// otherwise always connect directly. Costs money per GB while it is on; never ship it enabled.
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index e2e870445..05f12b5f1 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1100,6 +1100,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
streamingAvailable: terminalBackends.some((backend) => !!backend.openStream),
diagnostic: (event, fields) => console.log(`[terminal-stream] ${event}`, fields),
+ typingTrace: env.TYPING_TRACE ? (line) => console.log(`[typing] ${line}`) : undefined,
// The keystroke prewarm (grid-reads-without-waking issue 03): typing into a pane whose agent runs on
// a sleeping grid starts that grid while the person types. Here, in the daemon's own input path, so
// an older desktop and typing from a phone get it too; an agent on its own login has no `grid`.
diff --git a/cli/src/gateway/gateway.spec.ts b/cli/src/gateway/gateway.spec.ts
index 444eceae3..544727a98 100644
--- a/cli/src/gateway/gateway.spec.ts
+++ b/cli/src/gateway/gateway.spec.ts
@@ -12,11 +12,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import type { BackendSocket } from '../backendSocket.js'
import type { Asker } from '../core/api.js'
import * as C from '../lib/e2ee/core.js'
-import { TerminalBinaryKind } from '../lib/terminalBinary.js'
+import { deriveTerminalBinaryKey, sealTerminalBinary } from '../lib/e2ee/terminalSeal.js'
+import { TerminalBinaryKind, type TerminalBinaryClear } from '../lib/terminalBinary.js'
import { bindMessageRequest } from '../testing/socketCore.js'
import { dispatchDown, gatewayOf, relaySocket, upstreamOf } from '../testing/relaySocket.js'
import type { DeviceLogTrustOutcome } from '../lib/e2ee/deviceLogSyncer.js'
import { unknownHelloReader } from './start.js'
+import { env } from '../config/env.js'
/** The machine the sessions are bound to: every hello and welcome is signed over it. */
const MACHINE = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'
@@ -72,13 +74,17 @@ async function pairedClient(socket: BackendSocket, connId: string, opts: { role?
store.addPaired(pub, opts.label ?? 'Dee’s phone', Date.now(), opts.role ?? 'web', { shared: opts.shared })
const eph = C.newEphemeral()
await dispatchDown(socket, { type: 'e2e_hello', payload: { identityPub: pub, ephPub: C.b64e(eph.pub), sig: C.b64e(C.helloSig(identity.priv, MACHINE, eph.pub)) } }, connId)
- const welcome = queuedFor(socket, connId).find((frame) => frame.type === 'e2e_welcome')!
+ // The latest: a second hello on a connection replaces its session.
+ const welcome = queuedFor(socket, connId).filter((frame) => frame.type === 'e2e_welcome').at(-1)!
const p = welcome.payload as Record<string, string>
const keys = C.sessionKeys(eph.priv, C.b64d(p.ephPub), MACHINE, eph.pub, C.b64d(p.ephPub))
let sent = 0
+ let sentBinary = 0
return {
pub,
seal: (type: string, payload: Record<string, unknown>): Frame => ({ type, payload: C.wrapPayload(keys.c2s, 'p', sent++, type, undefined, payload) }),
+ /** Terminal bytes, sealed as the app seals a keystroke. */
+ sealBinary: (frame: TerminalBinaryClear): Uint8Array => sealTerminalBinary(deriveTerminalBinaryKey(keys.c2s), sentBinary++, frame)!,
open: (frame: Frame): unknown => C.unwrapPayload(keys.s2c, (frame.payload as C.WrappedPayload).__e2e, String(frame.type), undefined),
}
}
@@ -252,6 +258,226 @@ describe('terminal streams on a client\'s P2P channel', () => {
expect(viaP2p.calls).toBe(1)
await socket.stop()
})
+
+ /** A phone with one live stream, and a way to tell which wire that stream's output takes. */
+ async function streamOnPhone() {
+ const socket = relaySocket(MACHINE)
+ const gateway = gatewayOf(socket)
+ const p2p = (gateway as unknown as { terminalP2p: { send(connId: string, data: unknown): boolean } }).terminalP2p
+ const send = vi.spyOn(p2p, 'send').mockReturnValue(true)
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const phone = await pairedClient(socket, 'phone-1')
+ const STREAM = '00000000-0000-4000-8000-000000000003'
+ gateway.terminal('phone-1', 'terminal_ready', { requestId: 'open-1', streamId: STREAM })
+ const outputRides = (): 'p2p' | 'relay' => {
+ const before = send.mock.calls.length
+ gateway.terminalBinary('phone-1', { kind: TerminalBinaryKind.output, streamId: STREAM, seq: 1, compressed: false, bytes: new Uint8Array([104]) })
+ return send.mock.calls.length > before ? 'p2p' : 'relay'
+ }
+ const logged = () => log.mock.calls.map((call) => String(call[0])).filter((line) => line.startsWith('[terminal-p2p]'))
+ return { socket, gateway, phone, STREAM, outputRides, logged }
+ }
+
+ it.each(['terminal_ack', 'terminal_alive', 'terminal_resize', 'terminal_scroll', 'terminal_resync'])(
+ 'keeps a stream on P2P when a relay %s the client sealed before moving it arrives after the move',
+ async (type) => {
+ // 2026-10-15: the phone's relay ack, sealed ~16ms before its P2P resync, reached the machine after it
+ // and took the stream back off P2P; the phone saw relay output and dropped its whole channel.
+ const { socket, phone, STREAM, outputRides, logged } = await streamOnPhone()
+ const stale = phone.seal(type, { streamId: STREAM, lastSeq: 1, resizeSeq: 1, cols: 80, rows: 24, direction: 'up', lines: 1 })
+ const move = phone.seal('terminal_resync', { streamId: STREAM })
+ await dispatchDown(socket, move, 'phone-1', 'p2p')
+ expect(outputRides()).toBe('p2p')
+ await dispatchDown(socket, stale, 'phone-1', 'relay')
+ expect(outputRides()).toBe('p2p')
+ expect(logged()).toEqual([
+ '[terminal-p2p] conn=phone-1 stream=00000000 route=p2p by=terminal_resync n=1',
+ `[terminal-p2p] conn=phone-1 stream=00000000 kept on p2p: relay "${type}" n=0 was sealed before the move (n=1)`,
+ ])
+ await socket.stop()
+ },
+ )
+
+ it('says a stale relay frame once per move, not once per frame', async () => {
+ const { socket, phone, STREAM, logged } = await streamOnPhone()
+ const stale = [phone.seal('terminal_ack', { streamId: STREAM, lastSeq: 1 }), phone.seal('terminal_ack', { streamId: STREAM, lastSeq: 2 })]
+ await dispatchDown(socket, phone.seal('terminal_resync', { streamId: STREAM }), 'phone-1', 'p2p')
+ for (const frame of stale) await dispatchDown(socket, frame, 'phone-1', 'relay')
+ expect(logged().filter((line) => line.includes('kept on p2p'))).toHaveLength(1)
+ await socket.stop()
+ })
+
+ it('moves a stream back to the relay on a relay frame sealed after the move, and says so', async () => {
+ // The phone's quiet one-stream demotion sends no resync: its next ack over the relay is the whole signal.
+ const { socket, phone, STREAM, outputRides, logged } = await streamOnPhone()
+ await dispatchDown(socket, phone.seal('terminal_resync', { streamId: STREAM }), 'phone-1', 'p2p')
+ await dispatchDown(socket, phone.seal('terminal_ack', { streamId: STREAM, lastSeq: 1 }), 'phone-1', 'relay')
+ expect(outputRides()).toBe('relay')
+ expect(logged().at(-1)).toBe('[terminal-p2p] conn=phone-1 stream=00000000 route=relay by="terminal_ack" n=1')
+ // And it may move onto P2P again with a newer resync.
+ await dispatchDown(socket, phone.seal('terminal_resync', { streamId: STREAM }), 'phone-1', 'p2p')
+ expect(outputRides()).toBe('p2p')
+ await socket.stop()
+ })
+
+ it('keeps a stream on the relay when the client\'s newer relay resync overtakes an older P2P one', async () => {
+ // A P2P channel that stalled (an SCTP retransmit takes a second) delivers late: the client had already
+ // moved the stream back, and a resync it sealed before that must not move it onto P2P again.
+ const { socket, phone, STREAM, outputRides } = await streamOnPhone()
+ const olderMove = phone.seal('terminal_resync', { streamId: STREAM })
+ const newerBack = phone.seal('terminal_resync', { streamId: STREAM })
+ await dispatchDown(socket, newerBack, 'phone-1', 'relay')
+ await dispatchDown(socket, olderMove, 'phone-1', 'p2p')
+ expect(outputRides()).toBe('relay')
+ await socket.stop()
+ })
+
+ it('starts a stream opened over P2P on P2P, at the open\'s counter', async () => {
+ const socket = relaySocket(MACHINE)
+ const gateway = gatewayOf(socket)
+ const p2p = (gateway as unknown as { terminalP2p: { send(connId: string, data: unknown): boolean } }).terminalP2p
+ const send = vi.spyOn(p2p, 'send').mockReturnValue(true)
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const phone = await pairedClient(socket, 'phone-1')
+ const STREAM = '00000000-0000-4000-8000-000000000004'
+ await dispatchDown(socket, phone.seal('terminal_open', { requestId: 'open-p2p', agentId: 'a1', cols: 80, rows: 24 }), 'phone-1', 'p2p')
+ gateway.terminal('phone-1', 'terminal_ready', { requestId: 'open-p2p', streamId: STREAM })
+ const before = send.mock.calls.length
+ gateway.terminalBinary('phone-1', { kind: TerminalBinaryKind.output, streamId: STREAM, seq: 1, compressed: false, bytes: new Uint8Array([104]) })
+ expect(send.mock.calls.length).toBe(before + 1)
+ // A relay frame sealed after the open is the client moving it back.
+ await dispatchDown(socket, phone.seal('terminal_ack', { streamId: STREAM, lastSeq: 1 }), 'phone-1', 'relay')
+ gateway.terminalBinary('phone-1', { kind: TerminalBinaryKind.output, streamId: STREAM, seq: 2, compressed: false, bytes: new Uint8Array([104]) })
+ expect(send.mock.calls.length).toBe(before + 1)
+ await socket.stop()
+ })
+
+ it('counts a new session on the same connection from the start again', async () => {
+ // A hello on a connection replaces its session, and the new session's counters begin at 0: a counter
+ // kept from the old one would have pinned the stream to P2P for good.
+ const { socket, phone, STREAM, outputRides } = await streamOnPhone()
+ for (let i = 0; i < 4; i++) phone.seal('terminal_alive', { streamId: STREAM })
+ await dispatchDown(socket, phone.seal('terminal_resync', { streamId: STREAM }), 'phone-1', 'p2p')
+ expect(outputRides()).toBe('p2p')
+ const again = await pairedClient(socket, 'phone-1')
+ await dispatchDown(socket, again.seal('terminal_ack', { streamId: STREAM, lastSeq: 1 }), 'phone-1', 'relay')
+ expect(outputRides()).toBe('relay')
+ await socket.stop()
+ })
+})
+
+describe('a client\'s terminal bytes, on their way to the core', () => {
+ const STREAM = '00000000-0000-4000-8000-000000000005'
+ const key = (seq: number): TerminalBinaryClear => ({ kind: TerminalBinaryKind.input, streamId: STREAM, seq, bytes: new TextEncoder().encode(`k${seq}`), compressed: false })
+
+ /** The gateway's own way in, as the backend link and a P2P channel feed it — in line, not dispatched directly. */
+ const arrive = (socket: ReturnType<typeof relaySocket>) => {
+ const gateway = gatewayOf(socket) as unknown as {
+ enqueueDown(frame: Frame, connId: string, transport: 'relay' | 'p2p'): void
+ enqueueTerminalBinary(connId: string, raw: Uint8Array): void
+ }
+ return {
+ frame: (frame: Frame, transport: 'relay' | 'p2p' = 'relay') => gateway.enqueueDown(frame, 'phone-1', transport),
+ bytes: (raw: Uint8Array) => gateway.enqueueTerminalBinary('phone-1', raw),
+ }
+ }
+
+ it('reach the core while the client\'s P2P offer is still being answered', async () => {
+ // Answering an offer awaits a STUN race and ICE gathering, 0.1–0.7s and up to 5s; in line with the
+ // rest, it held every keystroke the client sent after it.
+ const socket = relaySocket(MACHINE)
+ const phone = await pairedClient(socket, 'phone-1')
+ const p2p = (gatewayOf(socket) as unknown as { terminalP2p: { handleSignal(connId: string, type: string, value: unknown): Promise<boolean> } }).terminalP2p
+ let answered!: () => void
+ const answering = new Promise<void>((resolve) => { answered = resolve })
+ const signals: string[] = []
+ vi.spyOn(p2p, 'handleSignal').mockImplementation(async (_connId, type) => { signals.push(type); if (type === 'p2p_offer') await answering; return true })
+ const core = vi.spyOn(socket.fromGateway, 'binary').mockImplementation(() => {})
+ const into = arrive(socket)
+ into.frame(phone.seal('p2p_offer', { sessionId: 's1', sdp: 'v=0', protocolVersion: 1 }))
+ into.frame(phone.seal('p2p_ice_candidate', { sessionId: 's1', candidate: null, protocolVersion: 1 }))
+ into.bytes(phone.sealBinary(key(1)))
+ await vi.waitFor(() => expect(signals).toEqual(['p2p_offer']))
+ expect(core).toHaveBeenCalledWith('phone-1', key(1))
+ // The candidate still waits for its offer: it has no responder to reach before the answer.
+ answered()
+ await vi.waitFor(() => expect(signals).toEqual(['p2p_offer', 'p2p_ice_candidate']))
+ await socket.stop()
+ })
+
+ it('reach the core while the client\'s requests wait at the gate, and are opened under the session they were sealed for', async () => {
+ // A hello that replaces the session, still waiting in line, must not leave the bytes sealed under the
+ // old one unopenable.
+ const socket = relaySocket(MACHINE)
+ const phone = await pairedClient(socket, 'phone-1')
+ const core = vi.spyOn(socket.fromGateway, 'binary').mockImplementation(() => {})
+ socket.holdRequests()
+ const into = arrive(socket)
+ const identity = C.newIdentity()
+ const eph = C.newEphemeral()
+ into.frame({ type: 'e2e_hello', payload: { identityPub: C.b64e(identity.pub), ephPub: C.b64e(eph.pub), sig: C.b64e(C.helloSig(identity.priv, MACHINE, eph.pub)) } })
+ into.bytes(phone.sealBinary(key(1)))
+ into.bytes(phone.sealBinary(key(2)))
+ expect(core.mock.calls).toEqual([['phone-1', key(1)], ['phone-1', key(2)]])
+ socket.openRequests()
+ await socket.stop()
+ })
+
+ it('that no session opens are refused with the session-gone notice, not passed on', async () => {
+ const socket = relaySocket(MACHINE)
+ const phone = await pairedClient(socket, 'phone-1')
+ const core = vi.spyOn(socket.fromGateway, 'binary').mockImplementation(() => {})
+ gatewayOf(socket).e2ee.dropSession('phone-1')
+ arrive(socket).bytes(phone.sealBinary(key(1)))
+ expect(core).not.toHaveBeenCalled()
+ expect(queuedFor(socket, 'phone-1').at(-1)).toEqual({ type: 'e2e_session_unknown', payload: { refused: { type: 'terminal_binary', kind: TerminalBinaryKind.input, n: 0 } } })
+ await socket.stop()
+ })
+
+ it('are traced with the wire they came on while tracing is on, never with what they carry', async () => {
+ const socket = relaySocket(MACHINE)
+ const phone = await pairedClient(socket, 'phone-1')
+ vi.spyOn(socket.fromGateway, 'binary').mockImplementation(() => {})
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const was = env.TYPING_TRACE
+ ;(env as { TYPING_TRACE: boolean }).TYPING_TRACE = true
+ try {
+ const gateway = gatewayOf(socket) as unknown as { handleP2pData(connId: string, data: Uint8Array): void }
+ arrive(socket).bytes(phone.sealBinary(key(1)))
+ gateway.handleP2pData('phone-1', phone.sealBinary(key(2)))
+ arrive(socket).bytes(phone.sealBinary({ ...key(3), kind: TerminalBinaryKind.paste }))
+ const traced = log.mock.calls.map((call) => String(call[0])).filter((line) => line.startsWith('[typing]'))
+ expect(traced).toEqual([
+ '[typing] in conn=phone-1 stream=00000000 seq=1 2B via=relay',
+ '[typing] in conn=phone-1 stream=00000000 seq=2 2B via=p2p',
+ '[typing] in conn=phone-1 stream=00000000 paste 2B via=relay',
+ ])
+ expect(traced.join('\n')).not.toMatch(/k1|k2|k3/)
+ } finally {
+ ;(env as { TYPING_TRACE: boolean }).TYPING_TRACE = was
+ await socket.stop()
+ }
+ })
+
+ it('that the core fails on are said in the log, and the next ones still go', async () => {
+ const socket = relaySocket(MACHINE)
+ const phone = await pairedClient(socket, 'phone-1')
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const core = vi.spyOn(socket.fromGateway, 'binary')
+ .mockImplementationOnce(() => Promise.reject(new Error('core gone')))
+ .mockImplementationOnce(() => { throw new Error('core threw') })
+ .mockImplementation(() => {})
+ const into = arrive(socket)
+ into.bytes(phone.sealBinary(key(1)))
+ into.bytes(phone.sealBinary(key(2)))
+ into.bytes(phone.sealBinary(key(3)))
+ expect(core).toHaveBeenCalledTimes(3)
+ await vi.waitFor(() => expect(error.mock.calls).toEqual([
+ ['[backend] binary terminal dispatch failed:', 'core threw'],
+ ['[backend] binary terminal dispatch failed:', 'core gone'],
+ ]))
+ await socket.stop()
+ })
})
describe('the Wi-Fi device, over the gateway\'s sessions', () => {
diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.ts
index 37dbb469a..8054625d1 100644
--- a/cli/src/gateway/gateway.ts
+++ b/cli/src/gateway/gateway.ts
@@ -23,12 +23,12 @@ import type { AuthSessionManager } from '../lib/authSession.js'
import { shouldReplayCommander } from '../lib/commanderReplay.js'
import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from '../lib/deviceRecentTrim.js'
import { encryptRpcResult, rpcResultType } from '../lib/e2ee/applicationFrames.js'
-import { b64d, fingerprint, isWrapped } from '../lib/e2ee/core.js'
+import { b64d, fingerprint, isWrapped, type WrappedPayload } from '../lib/e2ee/core.js'
import { E2eeManager, type LinkedPeer, type PairResult } from '../lib/e2ee/manager.js'
import { MachinePeerStore } from '../lib/e2ee/machinePeers.js'
import { logFrame, sid } from '../lib/log.js'
import { BACKEND_ONLY_DOWN_TYPES, GATEWAY_REQUEST_TYPES, isLocalClientId, logSafeType } from '../lib/relayFrames.js'
-import { encodeTerminalHop, TerminalHopDirection, type TerminalBinaryClear } from '../lib/terminalBinary.js'
+import { encodeTerminalHop, TerminalBinaryKind, TerminalHopDirection, type TerminalBinaryClear } from '../lib/terminalBinary.js'
import {
TerminalP2pResponderPool,
TERMINAL_P2P_DOWN_TYPES,
@@ -67,8 +67,22 @@ export class RelayGateway implements GatewayPort {
private readonly link: UpstreamLink
private readonly core: GatewayEvents
private readonly terminalP2p: TerminalP2pResponderPool
- private readonly p2pPendingOpens = new Map<string, Set<string>>()
+ /** The `terminal_open`s a client sent over its P2P channel, by request id, each with the E2EE counter it was
+ * sealed under: the stream its `terminal_ready` names starts on P2P, decided at that counter. */
+ private readonly p2pPendingOpens = new Map<string, Map<string, number>>()
private readonly p2pStreams = new Map<string, Set<string>>()
+ /**
+ * Per client and stream, the E2EE counter of the frame that last decided which wire the stream's output
+ * rides. A client seals its frames in the order it decides, whichever wire carries them (one counter
+ * domain for both, lib/e2ee/replayWindow.ts), but the two wires deliver at different speeds: a relay
+ * `terminal_ack` the phone sealed just BEFORE its P2P resync arrived ~100–250ms after it, took the
+ * stream back off P2P, and the phone, seeing output on the relay again, dropped its whole channel and
+ * typed over the relay for ~4s while it dialled again (2026-10-15, `demoted · reason=relay_binary_received`
+ * 0.3–3s after `migrate · done`). A frame sealed before the decision in force is not a decision.
+ */
+ private readonly routeCounters = new Map<string, Map<string, number>>()
+ /** Streams whose stale relay frame has been logged since their last move onto P2P: once is enough. */
+ private readonly staleRouteLogged = new Set<string>()
/**
* The terminal streams each remote client has open, as the core's frames to it say: `terminal_ready`
* opens one, `terminal_closed` ends it. A stream a client moves onto its P2P channel must be one it
@@ -86,6 +100,8 @@ export class RelayGateway implements GatewayPort {
/** Appends to the device key log waiting for the backend's answer, by requestId. */
private readonly devlogAppends = new Map<string, (payload: Record<string, unknown> | null) => void>()
private readonly downChains = new Map<string, Promise<void>>()
+ /** P2P signalling, per connection, apart from `downChains` — see `enqueueDown`. */
+ private readonly signalChains = new Map<string, Promise<void>>()
/**
* Remote clients' frames wait here until the core is ready (`openRequests`), each in its connection's own
* order: the port answers long before start-up has wired every handler, and a request answered in
@@ -128,7 +144,7 @@ export class RelayGateway implements GatewayPort {
machineId, auth, computerId, autonomousEnv,
events: {
down: (frame, connId) => this.enqueueDown(frame, connId, 'relay'),
- binary: (connId, clientFrame) => this.enqueueTerminalBinary(connId, clientFrame),
+ binary: (connId, clientFrame) => this.enqueueTerminalBinary(connId, clientFrame, 'relay'),
up: () => this.onLinkUp?.(),
gone: () => this.linkGone(),
status: (connected) => this.core.status(connected),
@@ -146,6 +162,8 @@ export class RelayGateway implements GatewayPort {
onIdentityPaired: (connId, pub) => { if (this.directDeviceSinks.has(connId)) this.directDevicePins.set(connId, pub) },
onIdentityRevoked: identity => { this.deviceUnpaired(identity); this.onDirectDeviceRevoked?.(fingerprint(b64d(identity))) },
onSessionOpened: (connId, role, identity) => {
+ // A new session counts from the start again: a counter kept from the last one would pin its streams.
+ this.forgetRoutes(connId)
const peer = this.e2ee.pairedPeers().find(p => p.identityPub === identity)
this.core.client(connId, {
role, label: this.e2ee.sessionLabel(connId), identity, direct: this.directDeviceSinks.has(connId),
@@ -154,7 +172,10 @@ export class RelayGateway implements GatewayPort {
...(peer?.shared ? { guest: peer.sharedWith ?? '' } : {}),
})
},
- onSessionDropped: (connId) => this.core.client(connId, null),
+ onSessionDropped: (connId) => {
+ this.forgetRoutes(connId)
+ this.core.client(connId, null)
+ },
onPeerLinked: (peer) => {
// The mutual half of a password link: a machine that proved this one's password is pinned back,
// so this machine can dial it without that machine's own password.
@@ -198,6 +219,8 @@ export class RelayGateway implements GatewayPort {
this.p2pPendingOpens.clear()
this.p2pStreams.clear()
this.liveStreams.clear()
+ this.routeCounters.clear()
+ this.staleRouteLogged.clear()
this.replayCommanderOnNextSnapshot = true
}
@@ -425,9 +448,17 @@ export class RelayGateway implements GatewayPort {
// ── in, from remote clients ──────────────────────────────────────────────────────────────────────
+ /**
+ * A client's frame, in its connection's order. P2P signalling has an order of its own: answering an offer
+ * awaits a STUN race and ICE gathering (0.1–0.7s, 5s behind a dead STUN server), and in line with the
+ * rest it held every frame the client sent after it. An offer and its candidates still go one at a time,
+ * so a candidate never reaches a responder its offer has not built yet; a disconnect racing an offer is
+ * the pool's to settle (`offerSeq`, `stillCurrent`).
+ */
private enqueueDown(frame: Frame, connId: string, transport: RemoteTransport): void {
const key = connId || '__backend__'
- const previous = this.downChains.get(key) ?? Promise.resolve()
+ const chains = TERMINAL_P2P_SIGNAL_TYPES.has(frame.type as string) ? this.signalChains : this.downChains
+ const previous = chains.get(key) ?? Promise.resolve()
const next = previous
.catch(() => { /* prior failure is already logged */ })
.then(() => this.requestGate)
@@ -436,28 +467,35 @@ export class RelayGateway implements GatewayPort {
console.error('[backend] down-frame dispatch failed:', err instanceof Error ? err.message : err)
})
.finally(() => {
- if (this.downChains.get(key) === next) this.downChains.delete(key)
+ if (chains.get(key) === next) chains.delete(key)
})
- this.downChains.set(key, next)
+ chains.set(key, next)
}
- private enqueueTerminalBinary(connId: string, raw: Uint8Array): void {
- const key = connId || '__backend__'
- const previous = this.downChains.get(key) ?? Promise.resolve()
- const next = previous
- .catch(() => { /* prior failure is already logged */ })
- .then(async () => {
- const clear = this.e2ee.unwrapTerminalBinary(connId, raw)
- if (clear) await this.core.binary(connId, clear)
- else { const gone = this.e2ee.terminalSessionGone(connId, raw); if (gone) this.sendTo(connId, gone) }
- })
- .catch((err) => {
+ /**
+ * A client's terminal bytes (keystrokes, a paste, an upload's chunks): opened as they arrive, in the order
+ * they arrive, and handed to the core at once. They used to wait in line behind the connection's JSON
+ * frames, and with them behind whatever those awaited: a P2P offer's answer here, and in one process
+ * (`HARNESSD_SERVICES=none`) the core's own handling of each frame, a resize's keyframe included.
+ * Nothing a JSON frame does is a precondition for a keystroke: a stream exists only once the client was
+ * told so (`terminal_ready`), the session that opens these bytes only once it was welcomed, and the
+ * core keeps each stream's bytes in their order (backendSocket.ts `enqueueTerminalBinary`). Opened here
+ * rather than later, a hello that replaces this connection's session cannot leave the bytes sealed under
+ * the old one unopenable.
+ */
+ private enqueueTerminalBinary(connId: string, raw: Uint8Array, via: RemoteTransport = 'relay'): void {
+ try {
+ const clear = this.e2ee.unwrapTerminalBinary(connId, raw)
+ if (!clear) { const gone = this.e2ee.terminalSessionGone(connId, raw); if (gone) this.sendTo(connId, gone); return }
+ if (env.TYPING_TRACE && (clear.kind === TerminalBinaryKind.input || clear.kind === TerminalBinaryKind.paste)) {
+ console.log(`[typing] in conn=${sid(connId)} stream=${sid(clear.streamId)} ${clear.kind === TerminalBinaryKind.paste ? 'paste' : `seq=${clear.seq}`} ${clear.bytes.length}B via=${via}`)
+ }
+ void Promise.resolve(this.core.binary(connId, clear)).catch((err) => {
console.error('[backend] binary terminal dispatch failed:', err instanceof Error ? err.message : err)
})
- .finally(() => {
- if (this.downChains.get(key) === next) this.downChains.delete(key)
- })
- this.downChains.set(key, next)
+ } catch (err) {
+ console.error('[backend] binary terminal dispatch failed:', err instanceof Error ? err.message : err)
+ }
}
/**
@@ -568,7 +606,8 @@ export class RelayGateway implements GatewayPort {
await this.manage(connId, type, payload)
return
}
- if (type.startsWith('terminal_')) this.noteTerminalInputRoute(connId, type, payload, transport)
+ // `unwrapDown` opened it, so its envelope counter is a number.
+ if (type.startsWith('terminal_')) this.noteTerminalInputRoute(connId, type, payload, transport, (frame.payload as WrappedPayload).__e2e.n)
await this.core.frame(connId, opened, transport, role)
}
@@ -608,6 +647,7 @@ export class RelayGateway implements GatewayPort {
this.p2pPendingOpens.delete(connId)
this.p2pStreams.delete(connId)
this.liveStreams.delete(connId)
+ this.forgetRoutes(connId)
await this.core.disconnected(connId)
return
}
@@ -759,7 +799,7 @@ export class RelayGateway implements GatewayPort {
return
}
if (data.length > 512 * 1024) return
- this.enqueueTerminalBinary(connId, data)
+ this.enqueueTerminalBinary(connId, data, 'p2p')
}
/** What the core has told a remote client about its terminal streams: one opened, one closed. */
@@ -774,50 +814,102 @@ export class RelayGateway implements GatewayPort {
const streams = this.liveStreams.get(connId)
streams?.delete(streamId)
if (streams?.size === 0) this.liveStreams.delete(connId)
+ this.forgetRoutes(connId, streamId)
}
}
+ /**
+ * Which wire a client's frame says its stream's output should ride, read from the frame's E2EE
+ * [counter] — see `routeCounters`. Only a frame sealed AFTER the decision in force can change it:
+ * - a `terminal_resync` over P2P moves a live stream onto P2P (live migration: remoteRelay.ts and the
+ * phone send a SECOND resync over the channel once it is ready, after the first, over the relay,
+ * drained and snapshotted the stream). The live-stream check guards against promoting a streamId
+ * whose pane was closed in the same instant the migration was in flight;
+ * - any `terminal_*` frame for the stream over the relay moves it back: a client demotes with a relay
+ * resync, or, for one stream, by simply sending its next frame (an ack, `terminal_alive`) over the relay.
+ * A relay frame sealed before the stream moved onto P2P changes nothing, and neither does a P2P frame
+ * sealed before the client moved it back.
+ */
private noteTerminalInputRoute(
connId: string,
type: string,
payload: Record<string, unknown>,
transport: RemoteTransport,
+ counter: number,
): void {
if (type === 'terminal_open' && typeof payload.requestId === 'string') {
let pending = this.p2pPendingOpens.get(connId)
- if (!pending) { pending = new Set(); this.p2pPendingOpens.set(connId, pending) }
- if (transport === 'p2p') pending.add(payload.requestId)
+ if (!pending) { pending = new Map(); this.p2pPendingOpens.set(connId, pending) }
+ if (transport === 'p2p') pending.set(payload.requestId, counter)
else pending.delete(payload.requestId)
return
}
const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''
- // Live-migration promotion: the client's remoteRelay.ts sends a SECOND terminal_resync over p2p
- // (after the first one, over relay, already drained/snapshotted the stream) once its own p2p
- // channel is ready — arriving here is our signal to start routing this stream's OUTPUT over p2p
- // too, mirroring what the client just did on its side. The live-stream check guards against
- // promoting a streamId whose pane was closed in the same instant the migration was in flight.
- if (type === 'terminal_resync' && transport === 'p2p' && streamId
- && this.liveStreams.get(connId)?.has(streamId)) {
- let streams = this.p2pStreams.get(connId)
- if (!streams) { streams = new Set(); this.p2pStreams.set(connId, streams) }
- streams.add(streamId)
+ // Only a stream the core told this client it has has a route to decide (and a counter worth keeping).
+ if (!streamId || !this.liveStreams.get(connId)?.has(streamId)) return
+ const decided = this.routeCounters.get(connId)?.get(streamId) ?? -1
+ if (counter <= decided) {
+ if (transport !== 'p2p' && this.p2pStreams.get(connId)?.has(streamId)) this.logStaleRoute(connId, streamId, type, counter, decided)
+ return
+ }
+ if (type === 'terminal_resync' && transport === 'p2p') {
+ this.routeToP2p(connId, streamId, counter, 'terminal_resync')
return
}
- if (transport !== 'p2p' && streamId) this.p2pStreams.get(connId)?.delete(streamId)
+ if (transport === 'p2p') return
+ this.decideRoute(connId, streamId, counter)
+ if (this.p2pStreams.get(connId)?.delete(streamId)) {
+ if (this.p2pStreams.get(connId)!.size === 0) this.p2pStreams.delete(connId)
+ console.log(`[terminal-p2p] conn=${sid(connId)} stream=${sid(streamId)} route=relay by=${logSafeType(type)} n=${counter}`)
+ }
+ }
+
+ private routeToP2p(connId: string, streamId: string, counter: number, by: string): void {
+ this.decideRoute(connId, streamId, counter)
+ this.staleRouteLogged.delete(`${connId}\0${streamId}`)
+ let streams = this.p2pStreams.get(connId)
+ if (!streams) { streams = new Set(); this.p2pStreams.set(connId, streams) }
+ if (streams.has(streamId)) return
+ streams.add(streamId)
+ console.log(`[terminal-p2p] conn=${sid(connId)} stream=${sid(streamId)} route=p2p by=${by} n=${counter}`)
+ }
+
+ private decideRoute(connId: string, streamId: string, counter: number): void {
+ let streams = this.routeCounters.get(connId)
+ if (!streams) { streams = new Map(); this.routeCounters.set(connId, streams) }
+ streams.set(streamId, counter)
+ }
+
+ /** A relay frame sealed before its stream moved onto P2P, kept from undoing the move: said once per move. */
+ private logStaleRoute(connId: string, streamId: string, type: string, counter: number, decided: number): void {
+ const key = `${connId}\0${streamId}`
+ if (this.staleRouteLogged.has(key)) return
+ this.staleRouteLogged.add(key)
+ console.log(`[terminal-p2p] conn=${sid(connId)} stream=${sid(streamId)} kept on p2p: relay ${logSafeType(type)} n=${counter} was sealed before the move (n=${decided})`)
+ }
+
+ /** Forget the routing decisions for one stream, or for every stream of a connection. */
+ private forgetRoutes(connId: string, streamId?: string): void {
+ if (streamId === undefined) {
+ this.routeCounters.delete(connId)
+ for (const key of this.staleRouteLogged) if (key.startsWith(`${connId}\0`)) this.staleRouteLogged.delete(key)
+ return
+ }
+ const streams = this.routeCounters.get(connId)
+ streams?.delete(streamId)
+ if (streams?.size === 0) this.routeCounters.delete(connId)
+ this.staleRouteLogged.delete(`${connId}\0${streamId}`)
}
private routeTerminalOutputToP2p(connId: string, type: string, payload: Record<string, unknown>): boolean {
const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''
const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''
const pending = this.p2pPendingOpens.get(connId)
- if ((type === 'terminal_ready' || type === 'terminal_error') && requestId && pending?.has(requestId)) {
- pending.delete(requestId)
- if (pending.size === 0) this.p2pPendingOpens.delete(connId)
- if (type === 'terminal_ready' && streamId) {
- let streams = this.p2pStreams.get(connId)
- if (!streams) { streams = new Set(); this.p2pStreams.set(connId, streams) }
- streams.add(streamId)
- }
+ const openedAt = requestId ? pending?.get(requestId) : undefined
+ if ((type === 'terminal_ready' || type === 'terminal_error') && openedAt !== undefined) {
+ pending!.delete(requestId)
+ if (pending!.size === 0) this.p2pPendingOpens.delete(connId)
+ if (type === 'terminal_ready' && streamId) this.routeToP2p(connId, streamId, openedAt, 'terminal_open')
return true
}
const streams = this.p2pStreams.get(connId)
@@ -832,6 +924,7 @@ export class RelayGateway implements GatewayPort {
private demoteP2pConnection(connId: string, reason: string): void {
this.p2pPendingOpens.delete(connId)
this.p2pStreams.delete(connId)
+ this.forgetRoutes(connId)
console.warn(`[terminal-p2p] conn=${sid(connId)} fallback=relay reason=${reason}`)
}
diff --git a/cli/src/lib/terminalP2p.spec.ts b/cli/src/lib/terminalP2p.spec.ts
index 732280e6f..e45b4b146 100644
--- a/cli/src/lib/terminalP2p.spec.ts
+++ b/cli/src/lib/terminalP2p.spec.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import {
+ describePair,
isRelayedPair,
readTurn,
relayCanReach,
@@ -45,15 +46,23 @@ describe('terminal WebRTC data channel', () => {
onData: (data) => resolveInitiatorData(typeof data === 'string' ? Buffer.from(data) : data),
})
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
try {
initiator.start()
expect(await initiator.waitUntilReady(5_000)).toBe(true)
expect(initiator.send('terminal-input')).toBe(true)
expect(await responderData).toBe('terminal-input')
+ // The answering side says where its time went: the phone times only its own steps.
+ const said = log.mock.calls.map((call) => String(call[0])).filter((line) => line.startsWith('[terminal-p2p] conn=source-1'))
+ expect(said).toEqual([
+ expect.stringMatching(/^\[terminal-p2p\] conn=source-1 answered \+\d+ms after the offer \(stun \d+ms, peer library \d+ms, gather and answer \d+ms\)$/),
+ expect.stringMatching(/^\[terminal-p2p\] conn=source-1 channel open \+\d+ms after the offer, over host→host \(direct\)$/),
+ ])
expect(responder.send('source-1', Buffer.from([0x48, 0x54, 0x52, 0x4d]))).toBe(true)
expect(await initiatorData).toEqual(Buffer.from([0x48, 0x54, 0x52, 0x4d]))
} finally {
+ log.mockRestore()
await initiator.stop('test_complete', false)
await responder.stop()
}
@@ -153,6 +162,43 @@ describe('terminal WebRTC data channel', () => {
}
})
+ it('builds no responder for a connection that went away while its offer was in the stun race', async () => {
+ // The gateway's P2P signals no longer wait behind the connection's other frames, so its disconnect can
+ // land while an offer is still racing STUN — and the responder used to be built anyway, a TURN
+ // allocation with it, for nobody, until the negotiation timeout.
+ let resolveOffer!: (payload: TerminalP2pSignal) => void
+ const offered = new Promise<TerminalP2pSignal>((resolve) => { resolveOffer = resolve })
+ const initiator = new TerminalP2pInitiator({
+ policy: { enabled: true, protocolVersion: 1, stunUrls: [], openWaitMs: 1_500 },
+ sendSignal: (type, payload) => { if (type === 'p2p_offer') resolveOffer(payload) },
+ onData: () => { /* no peer in this test */ },
+ selectStunUrls: async () => ({ urls: [], udpReachable: null }),
+ })
+ initiator.start()
+ const offer = await offered
+ await initiator.stop('test_complete', false)
+
+ let release!: (selection: { urls: string[]; udpReachable: boolean | null }) => void
+ const gate = new Promise<{ urls: string[]; udpReachable: boolean | null }>((resolve) => { release = resolve })
+ const signals: string[] = []
+ const responder = new TerminalP2pResponderPool({
+ sendSignal: (_connId, type) => { signals.push(type) },
+ onData: () => { /* no data in this test */ },
+ selectStunUrls: () => gate,
+ })
+ try {
+ const answering = responder.handleSignal('source-1', 'p2p_offer', offer)
+ await responder.closeConnection('source-1', 'client_disconnected', false)
+ release({ urls: [], udpReachable: null })
+ await answering
+ await new Promise((resolve) => setTimeout(resolve, 50))
+ expect(signals).toEqual([])
+ expect(responder.send('source-1', 'anything')).toBe(false)
+ } finally {
+ await responder.stop()
+ }
+ })
+
it('hands the responder the offered urls, filtered and capped, to race on its own', async () => {
const selectStunUrls = vi.fn<StunSelector>(async (urls) => ({ urls, udpReachable: true }))
const responder = new TerminalP2pResponderPool({
@@ -264,6 +310,15 @@ describe('terminal WebRTC data channel', () => {
expect(isRelayedPair(SRFLX)).toBe(false) // remote unknown
})
+ it('names the nominated pair by its candidate types and says when it crosses TURN', () => {
+ expect(describePair(HOST, HOST)).toBe('host→host (direct)')
+ expect(describePair(SRFLX, SRFLX)).toBe('srflx→srflx (direct)')
+ // A phone on 4G behind carrier NAT: its own relay candidate carries the pair.
+ expect(describePair(SRFLX, RELAY)).toBe('srflx→relay (TURN)')
+ expect(describePair(RELAY, HOST)).toBe('relay→host (TURN)')
+ expect(describePair(SRFLX)).toBe('srflx→? (direct)') // remote unknown
+ })
+
it('does not mistake a host address that merely contains the word', () => {
expect(isRelayedPair('candidate:1 1 udp 1 10.0.0.1 1 typ host raddr relay.example')).toBe(false)
})
diff --git a/cli/src/lib/terminalP2p.ts b/cli/src/lib/terminalP2p.ts
index 9a605e452..19beb34d9 100644
--- a/cli/src/lib/terminalP2p.ts
+++ b/cli/src/lib/terminalP2p.ts
@@ -242,6 +242,17 @@ export function isRelayedPair(local: string, remote?: string): boolean {
return relay.test(local) || (typeof remote === 'string' && relay.test(remote))
}
+/**
+ * The nominated pair as `<ours>→<peer's>` candidate types and whether it crosses TURN, for the
+ * channel-open line. A phone on 4G sits behind its carrier's NAT, so a direct pair is rare there and
+ * every key pays the round trip through Cloudflare instead; without this the log could not say which
+ * path a slow round of typing ran on.
+ */
+export function describePair(local: string, remote?: string): string {
+ const type = (line?: string): string => /\btyp (\w+)/.exec(line ?? '')?.[1] ?? '?'
+ return `${type(local)}→${type(remote)} (${isRelayedPair(local, remote) ? 'TURN' : 'direct'})`
+}
+
function channelCanSend(channel: RTCDataChannel | null): channel is RTCDataChannel {
return channel?.readyState === 'open'
&& channel.bufferedAmount < TERMINAL_P2P_MAX_BUFFERED_BYTES
@@ -553,6 +564,9 @@ interface ResponderEntry {
timeout: ReturnType<typeof setTimeout>
disconnectGraceTimer: ReturnType<typeof setTimeout> | null
closing: boolean
+ /** How the answer's time was spent, said once it is sent and once the channel opens: the phone's own log
+ * times only its side (offer to answer took ~0.7s on 2026-10-15, with no line here saying where). */
+ timing: { offeredAt: number; stunMs: number; libraryMs: number; turn: boolean }
}
/** Target side: one responder per authenticated source connId. */
@@ -646,6 +660,15 @@ export class TerminalP2pResponderPool {
}
async closeConnection(connId: string, reason = 'closed', notifyPeer = true): Promise<void> {
+ // A connection that is gone takes its offers still in flight with it. One inside its STUN race has no
+ // entry yet, and finding its generation unchanged it went on to build a responder — a TURN allocation
+ // with it — for nobody, kept to the negotiation timeout. P2P signals no longer queue behind the
+ // connection's other frames (the gateway's `signalChains`), which is what lets a disconnect overtake its
+ // offer (review, 2026-10-19).
+ if (reason === 'client_disconnected') {
+ this.offerSeq.delete(connId)
+ this.shadowOfferSeq.delete(connId)
+ }
const entry = this.entries.get(connId)
if (entry && !entry.closing) {
this.entries.delete(connId)
@@ -723,7 +746,9 @@ export class TerminalP2pResponderPool {
: []
// The offerer raced these too, and may well have landed on a different server. That is fine: a
// srflx candidate is each peer's own public address, so the two sides need not agree on who to ask.
+ const offeredAt = performance.now()
const selection = await this.selectStunUrls(offeredStunUrls)
+ const selectedAt = performance.now()
const { RTCPeerConnection } = await import('werift')
if (!stillCurrent()) return null
const turn = turnChoice(readTurn(payload.turn), selection.udpReachable)
@@ -735,6 +760,7 @@ export class TerminalP2pResponderPool {
ready: false,
closing: false,
disconnectGraceTimer: null,
+ timing: { offeredAt, stunMs: selectedAt - offeredAt, libraryMs: performance.now() - selectedAt, turn: !!turn },
timeout: setTimeout(() => {
if (entry.ready) this.deps.onUnavailable?.(connId, 'negotiation_timeout')
void (stillCurrent() ? this.closeConnection(connId, 'negotiation_timeout') : this.closeShadow(connId, 'negotiation_timeout'))
@@ -789,6 +815,9 @@ export class TerminalP2pResponderPool {
if (state === 'open') {
entry.ready = true
clearTimeout(entry.timeout)
+ const pair = entry.pc.iceTransports.map((t) => t.getSelectedCandidatePair?.()).find((p) => p?.local?.candidate)
+ const over = pair ? `, over ${describePair(pair.local.candidate, pair.remote?.candidate)}` : ''
+ console.log(`[terminal-p2p] conn=${connId.slice(0, 8)} channel open +${Math.round(performance.now() - entry.timing.offeredAt)}ms after the offer${over}`)
} else if ((state === 'closed' || state === 'closing') && entry.ready) {
entry.ready = false
if (this.entries.get(connId) === entry) this.deps.onUnavailable?.(connId, 'channel_closed')
@@ -832,6 +861,10 @@ export class TerminalP2pResponderPool {
protocolVersion: TERMINAL_P2P_PROTOCOL_VERSION,
sdp: local.sdp,
})
+ const { offeredAt, stunMs, libraryMs, turn } = entry.timing
+ const total = performance.now() - offeredAt
+ console.log(`[terminal-p2p] conn=${connId.slice(0, 8)} answered +${Math.round(total)}ms after the offer`
+ + ` (stun ${Math.round(stunMs)}ms, peer library ${Math.round(libraryMs)}ms, gather and answer ${Math.round(total - stunMs - libraryMs)}ms${turn ? ', with TURN' : ''})`)
} catch {
await close('answer_failed')
}
diff --git a/cli/src/lib/terminalP2pLoading.spec.ts b/cli/src/lib/terminalP2pLoading.spec.ts
index 9a3a1f68c..168352140 100644
--- a/cli/src/lib/terminalP2pLoading.spec.ts
+++ b/cli/src/lib/terminalP2pLoading.spec.ts
@@ -6,6 +6,9 @@ import { fileURLToPath } from 'node:url'
import { build } from 'esbuild'
import { expect, it } from 'vitest'
+/** The child's verdict, its last line: the pool says above it how its answer went (`[terminal-p2p] … answered`). */
+const lastLine = (output: string): string => output.trim().split('\n').at(-1)!
+
it('loads the real peer library once, only when a peer negotiation needs it', async () => {
// Found by QA on a quiet machine: a gateway paid for werift before any P2P traffic.
// Observe real module evaluation in a disposable split bundle, not Node's CommonJS cache.
@@ -90,7 +93,7 @@ it('loads the real peer library once, only when a peer negotiation needs it', as
cwd: cli, encoding: 'utf8', timeout: 15_000, maxBuffer: 1024 * 1024,
env: { ...process.env, NODE_OPTIONS: '' },
})
- expect(JSON.parse(output.trim())).toEqual({ evaluations: 1 })
+ expect(JSON.parse(lastLine(output))).toEqual({ evaluations: 1 })
// A missing split chunk costs only P2P. In particular begin() must not reject unhandled.
const peerChunk = readdirSync(root).find(name => name.startsWith('part-')
&& readFileSync(join(root, name), 'utf8').includes('globalThis.__qaPeerLibraryEvaluations ='))
@@ -100,7 +103,7 @@ it('loads the real peer library once, only when a peer negotiation needs it', as
cwd: cli, encoding: 'utf8', timeout: 15_000, maxBuffer: 1024 * 1024,
env: { ...process.env, NODE_OPTIONS: '', EXPECT_PEER_LOAD_FAILURE: '1' },
})
- expect(JSON.parse(unavailable.trim())).toEqual({ unavailable: true })
+ expect(JSON.parse(lastLine(unavailable))).toEqual({ unavailable: true })
} finally {
rmSync(root, { recursive: true, force: true })
}
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index 54ca72855..5726943b8 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -50,7 +50,12 @@ class FakeStream implements TerminalStreamHandle {
if (!this.holdWrites) return TERMINAL_ACTION_SUCCEEDED
return new Promise((resolve) => { this.pendingWrites.push(resolve) })
}
- async pasteRaw(text: string) { this.pastes.push(text); return TERMINAL_ACTION_SUCCEEDED }
+ /** When set, a paste waits on it, with the check the manager asked to be made as it lands. */
+ pasteLands: ((allowed: (() => boolean) | undefined) => Promise<TerminalActionResult>) | null = null
+ async pasteRaw(text: string, allowed?: () => boolean) {
+ this.pastes.push(text)
+ return this.pasteLands ? this.pasteLands(allowed) : TERMINAL_ACTION_SUCCEEDED
+ }
async resize(size: { cols: number; rows: number }) { this.sizes.push(size); return TERMINAL_ACTION_SUCCEEDED }
async scroll(direction: 'up' | 'down', lines: number) { this.scrolls.push({ direction, lines }); return TERMINAL_ACTION_SUCCEEDED }
async pauseOutput() { this.pauses++; return TERMINAL_ACTION_SUCCEEDED }
@@ -325,28 +330,33 @@ describe('TerminalStreamManager', () => {
kind: TerminalBinaryKind.input, streamId, seq: 0, compressed: false, bytes: Buffer.from('abc'),
})
expect(Buffer.from(stream.writes[0]).toString()).toBe('abc')
+ // Ahead of seq 1, which may still be on its way over the slower wire: it waits for it, and nothing is said.
await manager.handleBinary('web-1', {
kind: TerminalBinaryKind.input, streamId, seq: 2, compressed: false, bytes: Buffer.from('out-of-order'),
})
expect(stream.writes).toHaveLength(1)
- expect(sent.at(-1)?.payload.code).toBe('TERMINAL_INPUT_INVALID')
- // …and says which seq it is still waiting for, so a client that skipped a number can realign
- // instead of having every later keystroke refused.
- expect(sent.at(-1)?.payload).toMatchObject({ reason: 'seq', expectedSeq: 1, streamId })
+ expect(sent.map((frame) => frame.payload.code)).not.toContain('TERMINAL_INPUT_INVALID')
- // An oversized frame is refused the same way, with the counter untouched: the next accepted
- // seq is still 1.
+ // An oversized frame is refused at once, with the counter untouched: the next accepted seq is still 1. The client
+ // numbers its next keys from there, so the one waiting under its old numbering goes: released after them, it
+ // would land after keys typed later than it.
await manager.handleBinary('web-1', {
kind: TerminalBinaryKind.input, streamId, seq: 1, compressed: false, bytes: Buffer.alloc(64 * 1024 + 1, 0x61),
})
expect(stream.writes).toHaveLength(1)
expect(sent.at(-1)?.payload).toMatchObject({ code: 'TERMINAL_INPUT_INVALID', reason: 'size', expectedSeq: 1 })
+ // The realigned keys: seq 1, then 2, each written in turn.
const mouse = Buffer.from('\u001b[<0;12;8M')
await manager.handleBinary('web-1', {
kind: TerminalBinaryKind.input, streamId, seq: 1, compressed: false, bytes: mouse,
})
- expect(Buffer.from(stream.writes.at(-1)!).equals(mouse)).toBe(true)
+ await manager.handleBinary('web-1', {
+ kind: TerminalBinaryKind.input, streamId, seq: 2, compressed: false, bytes: Buffer.from('typed after'),
+ })
+ expect(stream.writes.map((bytes) => Buffer.from(bytes).toString())).toEqual(['abc', mouse.toString(), 'typed after'])
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(sent.filter((frame) => frame.payload.code === 'TERMINAL_INPUT_INVALID')).toHaveLength(1)
await manager.handleFrame('web-1', 'terminal_resize', {
streamId, resizeSeq: 0, cols: 140, rows: 50,
@@ -493,6 +503,186 @@ describe('TerminalStreamManager', () => {
expect(remote.bytes.length).toBeLessThan(big.length)
})
+ describe('keystrokes that come ahead of a missing one', () => {
+ // A client moving a stream from the relay onto its P2P channel sends key N over the relay and N+1 over the
+ // faster channel: N+1 came first, was refused, and the client's realignment lost two keys (2026-10-15).
+ const open = async () => {
+ await manager.handleFrame('web-1', 'terminal_open', { requestId: 'open-order', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40 })
+ const streamId = sent[0].payload.streamId as string
+ const key = (seq: number, text: string | Buffer = `k${seq}`) => manager.handleBinary('web-1', {
+ kind: TerminalBinaryKind.input, streamId, seq, compressed: false, bytes: typeof text === 'string' ? Buffer.from(text) : text,
+ })
+ const written = () => stream.writes.map((bytes) => Buffer.from(bytes).toString())
+ const refusals = () => sent.filter((frame) => frame.payload.code === 'TERMINAL_INPUT_INVALID').map((frame) => frame.payload)
+ return { streamId, key, written, refusals }
+ }
+
+ it('are written, in their order, as soon as the missing one arrives', async () => {
+ const { key, written, refusals } = await open()
+ await key(1)
+ await key(2)
+ expect(written()).toEqual([])
+ await key(0)
+ expect(written()).toEqual(['k0', 'k1', 'k2'])
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(refusals()).toEqual([])
+ })
+
+ it('go when the missing one does not come in time, and the client is told once what is expected', async () => {
+ const { streamId, key, written, refusals } = await open()
+ await key(0)
+ await key(2)
+ await key(3)
+ await vi.advanceTimersByTimeAsync(399)
+ expect(refusals()).toEqual([])
+ await vi.advanceTimersByTimeAsync(1)
+ expect(written()).toEqual(['k0'])
+ expect(refusals()).toEqual([expect.objectContaining({ streamId, reason: 'seq', expectedSeq: 1 })])
+ })
+
+ it('are refused at once after a wait was given up, until the expected one arrives', async () => {
+ // The client realigns on the refusal and numbers its next keys from there: a frame it numbered under the
+ // old count must not wait to land among them.
+ const { key, written, refusals } = await open()
+ await key(0)
+ await key(2)
+ await vi.advanceTimersByTimeAsync(400)
+ await key(5)
+ expect(refusals()).toHaveLength(2)
+ expect(refusals()[1]).toMatchObject({ expectedSeq: 1 })
+ await key(1, 'realigned')
+ await key(3)
+ expect(refusals()).toHaveLength(2)
+ await key(2, 'next')
+ expect(written()).toEqual(['k0', 'realigned', 'next', 'k3'])
+ })
+
+ it('give each gap a full wait of its own', async () => {
+ const { key, written, refusals } = await open()
+ await key(0)
+ await key(2)
+ await key(4)
+ await vi.advanceTimersByTimeAsync(300)
+ await key(1)
+ expect(written()).toEqual(['k0', 'k1', 'k2'])
+ await vi.advanceTimersByTimeAsync(399)
+ expect(refusals()).toEqual([])
+ await vi.advanceTimersByTimeAsync(1)
+ expect(refusals()).toEqual([expect.objectContaining({ expectedSeq: 3 })])
+ expect(written()).toEqual(['k0', 'k1', 'k2'])
+ })
+
+ it('are given up at once when more bytes wait than may be held', async () => {
+ const { key, written, refusals } = await open()
+ for (let seq = 1; seq <= 4; seq++) await key(seq, Buffer.alloc(64 * 1024, 0x61))
+ expect(refusals()).toEqual([])
+ await key(5, Buffer.alloc(1, 0x61))
+ expect(refusals()).toEqual([expect.objectContaining({ expectedSeq: 0 })])
+ await key(0)
+ expect(written()).toEqual(['k0'])
+ })
+
+ it('are given up at once when more frames wait than may be held', async () => {
+ const { key, written, refusals } = await open()
+ for (let seq = 1; seq <= 64; seq++) await key(seq)
+ expect(refusals()).toEqual([])
+ await key(65)
+ expect(refusals()).toEqual([expect.objectContaining({ expectedSeq: 0 })])
+ await key(0)
+ expect(written()).toEqual(['k0'])
+ })
+
+ it('go with any refusal, since the client numbers its next keys from what it is told', async () => {
+ // A number already written comes while one waits: the refusal realigns the client, and the key held under
+ // its old numbering would land among the new ones.
+ const { key, written, refusals } = await open()
+ await key(0)
+ await key(2)
+ await key(0, 'again')
+ expect(refusals()).toEqual([expect.objectContaining({ expectedSeq: 1 })])
+ await key(1, 'realigned')
+ await key(2, 'next')
+ expect(written()).toEqual(['k0', 'realigned', 'next'])
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(refusals()).toHaveLength(1)
+ })
+
+ it('keep the first of two frames under one number', async () => {
+ const { key, written, refusals } = await open()
+ await key(1, 'first')
+ await key(1, 'second')
+ await key(0)
+ expect(written()).toEqual(['k0', 'first'])
+ expect(refusals()).toEqual([])
+ })
+
+ it('are never written into a pane whose stream closed while they waited', async () => {
+ const { streamId, key, written, refusals } = await open()
+ await key(1)
+ await manager.handleFrame('web-1', 'terminal_close', { streamId })
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(written()).toEqual([])
+ expect(refusals()).toEqual([])
+ })
+
+ it('are traced, while tracing is on, by number and time and never by what was typed', async () => {
+ const lines: string[] = []
+ await manager.stop()
+ manager = newManager({ typingTrace: (line) => lines.push(line) })
+ const { streamId, key } = await open()
+ const short = streamId.slice(0, 8)
+ await key(1, 'secret-1')
+ await vi.advanceTimersByTimeAsync(30)
+ await key(0, 'secret-0')
+ sink!.onData(Buffer.from('echo'))
+ expect(lines).toEqual([
+ `stream=${short} seq=1 held: 0 has not come (1 waiting)`,
+ `stream=${short} seq=1..1 released after 30ms`,
+ `stream=${short} seq=1 first output out +0ms after it was written`,
+ ])
+ // A keystroke whose next screen goes out as a keyframe is said so.
+ await key(2, 'secret-2')
+ await manager.handleFrame('web-1', 'terminal_resize', { streamId, resizeSeq: 0, cols: 100, rows: 30 })
+ expect(lines.at(-1)).toBe(`stream=${short} seq=2 keyframe (resize) out +0ms after it was written`)
+ expect(lines.join('\n')).not.toContain('secret')
+ })
+
+ it('are given up before a paste, which never goes ahead of keys typed before it', async () => {
+ const { streamId, key, written, refusals } = await open()
+ await key(1)
+ await manager.handleBinary('web-1', { kind: TerminalBinaryKind.paste, streamId, seq: 0, compressed: false, bytes: Buffer.from('pasted') })
+ expect(refusals()).toEqual([expect.objectContaining({ expectedSeq: 0 })])
+ expect(stream.pastes).toEqual(['pasted'])
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(written()).toEqual([])
+ })
+ })
+
+ it('keeps a paste out of a pane whose stream closed while the paste was on its way, and says nothing', async () => {
+ // A stream's close no longer waits in line behind its paste (backendSocket.ts `enqueueTerminalBinary`):
+ // the paste must ask again as it lands, or it lands in a pane its client has let go.
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-paste-close', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,
+ })
+ const streamId = sent[0].payload.streamId as string
+ let land!: () => void
+ let askedAsItLanded: boolean | undefined
+ stream.pasteLands = (allowed) => new Promise((resolve) => {
+ land = () => {
+ askedAsItLanded = allowed?.()
+ resolve(askedAsItLanded ? TERMINAL_ACTION_SUCCEEDED : { state: 'failed', dispatch: 'not_started', reason: 'tmux paste-buffer could not be sent' })
+ }
+ })
+ const pasting = manager.handleBinary('web-1', { kind: TerminalBinaryKind.paste, streamId, seq: 0, compressed: false, bytes: new TextEncoder().encode('rm -rf build') })
+ await vi.waitFor(() => expect(stream.pastes).toEqual(['rm -rf build']))
+ await manager.handleFrame('web-1', 'terminal_close', { streamId })
+ const before = sent.length
+ land()
+ await pasting
+ expect(askedAsItLanded).toBe(false)
+ expect(sent.slice(before).map((frame) => frame.payload.code)).not.toContain('TERMINAL_PASTE_FAILED')
+ })
+
it('routes a binary paste kind to pasteRaw as one unit, never through writeRaw', async () => {
await manager.handleFrame('web-1', 'terminal_open', {
requestId: 'open-paste', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 036c38773..48d245902 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -92,6 +92,16 @@ const OUTPUT_FLUSH_MS = 8
const LOOPBACK_OUTPUT_FLUSH_MS = 2
const OUTPUT_CHUNK_BYTES = 32 * 1024
const INPUT_MAX_BYTES = 64 * 1024
+/**
+ * How long a keystroke that came ahead of the one before it waits for that one (`input`). A client moving a stream
+ * from the relay onto its P2P channel sends key N over the relay and key N+1 over the channel, the faster wire by
+ * ~150–250ms: N+1 came first and was refused, and the client's realignment lost N+1 and the key after it too
+ * (2026-10-15). Within a single wire nothing comes out of order; this only bridges the switch.
+ */
+const INPUT_REORDER_WAIT_MS = 400
+/** What may wait for the missing keystroke at most; past it the wait is given up at once. */
+const INPUT_REORDER_MAX_FRAMES = 64
+const INPUT_REORDER_MAX_BYTES = 256 * 1024
const PAUSE_HIGH_WATERMARK_BYTES = 384 * 1024
const RESUME_LOW_WATERMARK_BYTES = 128 * 1024
const RENDER_STALL_TIMEOUT_MS = 10_000
@@ -138,6 +148,17 @@ interface ActiveStream {
lastSyncAt: number
nextSeq: number
lastInputSeq: number
+ /** Keystrokes that came ahead of one still on its way, by their seq — see `input`. */
+ heldInput: Map<number, Uint8Array>
+ heldInputBytes: number
+ heldInputTimer: ReturnType<typeof setTimeout> | null
+ /** When the oldest keystroke still waiting began to wait (traced only). */
+ heldSince: number
+ /** The last keystroke written, until the first output after it goes out (traced only). */
+ echoProbe: { seq: number; at: number } | null
+ /** A wait was given up and the client told what was expected: nothing waits again until exactly that
+ * keystroke arrives, so a frame the client numbered under its old count never lands among its new ones. */
+ inputHoldOff: boolean
lastResizeSeq: number
pending: PendingOutput[]
pendingBytes: number
@@ -195,6 +216,9 @@ export interface TerminalStreamManagerDeps {
* pane opens can go to the phone the person is typing on (core/terminals/browser.ts).
*/
onInput?: (agentId: string, typed: boolean, from: { connId: string, kind: string | null; inputContext?: string; submitted?: boolean }) => void
+ /** Set only while keystrokes are traced (`TYPING_TRACE`): one line per keystroke held, released, and echoed.
+ * Numbers and timings only, never the bytes. */
+ typingTrace?: (line: string) => void
}
function sizeFrom(payload: FramePayload): TerminalStreamSize | null {
@@ -353,6 +377,9 @@ export class TerminalStreamManager {
return
}
if (frame.kind === TerminalBinaryKind.paste) {
+ // A paste carries no number to wait in line by: it must not go ahead of keystrokes typed before it, so
+ // any still waiting for a missing one are given up first, as they were before anything waited.
+ if (state.heldInput.size > 0) this.giveUpHeldInput(state)
await this.paste(state, frame.bytes)
return
}
@@ -580,6 +607,12 @@ export class TerminalStreamManager {
lastSyncAt: this.now(),
nextSeq: 0,
lastInputSeq: -1,
+ heldInput: new Map(),
+ heldInputBytes: 0,
+ heldInputTimer: null,
+ heldSince: 0,
+ echoProbe: null,
+ inputHoldOff: false,
lastResizeSeq: -1,
pending: [],
pendingBytes: 0,
@@ -674,26 +707,102 @@ export class TerminalStreamManager {
else if (state.outputPaused) this.armStallTimer(state)
}
+ /**
+ * One keystroke frame, written in its client's order. The next one expected is written at once, and with it any
+ * that came ahead of it and waited. One that comes ahead waits for the missing one (INPUT_REORDER_WAIT_MS), bounded
+ * by INPUT_REORDER_MAX_FRAMES/BYTES; when it does not come, everything waiting goes and the client is told, once,
+ * what was expected. Anything else — a number already used, a frame that is malformed — is refused at once, and
+ * what waited goes with it ([refuseInput]).
+ */
private async input(state: ActiveStream, inputSeq: number, bytes: Uint8Array): Promise<void> {
- if (!Number.isSafeInteger(inputSeq) || inputSeq !== state.lastInputSeq + 1 || bytes.length === 0 || bytes.length > INPUT_MAX_BYTES) {
- // Nothing here reached the pty, and `lastInputSeq` is deliberately left where it was. Say what
- // WOULD have been accepted: a client whose counter has drifted (a frame it dropped on its own
- // side while resyncing, say) can realign on `expectedSeq` and carry on, instead of having every
- // later keystroke refused too and treating a fine stream as a dead one.
- const expectedSeq = state.lastInputSeq + 1
- // A seq that is not a safe integer at all is an ordering fault too, as far as the client is concerned.
- const reason = bytes.length === 0 ? 'empty' : bytes.length > INPUT_MAX_BYTES ? 'size' : 'seq'
- this.sendError(state.connId, 'TERMINAL_INPUT_INVALID', {
- streamId: state.streamId,
- reason,
- expectedSeq,
- message: reason === 'seq'
- ? `input seq ${inputSeq} arrived, ${expectedSeq} expected`
- : reason === 'size' ? `input frame of ${bytes.length} bytes exceeds ${INPUT_MAX_BYTES}` : 'empty input frame',
- })
+ // A seq that is not a safe integer at all is an ordering fault too, as far as the client is concerned.
+ const malformed = !Number.isSafeInteger(inputSeq) ? 'seq' : bytes.length === 0 ? 'empty' : bytes.length > INPUT_MAX_BYTES ? 'size' : null
+ if (malformed) { this.refuseInput(state, malformed, inputSeq, bytes.length); return }
+ const expectedSeq = state.lastInputSeq + 1
+ if (inputSeq === expectedSeq) {
+ state.inputHoldOff = false
+ this.writeInput(state, inputSeq, bytes)
+ this.releaseHeldInput(state)
+ return
+ }
+ // A second frame under a number already waiting: the first one stands, and nothing is said about it.
+ if (inputSeq > expectedSeq && state.heldInput.has(inputSeq)) return
+ if (inputSeq > expectedSeq && !state.inputHoldOff) {
+ if (state.heldInput.size < INPUT_REORDER_MAX_FRAMES && state.heldInputBytes + bytes.length <= INPUT_REORDER_MAX_BYTES) {
+ if (state.heldInput.size === 0) state.heldSince = this.now()
+ this.deps.typingTrace?.(`stream=${state.streamId.slice(0, 8)} seq=${inputSeq} held: ${expectedSeq} has not come (${state.heldInput.size + 1} waiting)`)
+ state.heldInput.set(inputSeq, bytes)
+ state.heldInputBytes += bytes.length
+ state.heldInputTimer ??= setTimeout(() => this.giveUpHeldInput(state), INPUT_REORDER_WAIT_MS)
+ return
+ }
+ this.giveUpHeldInput(state)
return
}
+ this.refuseInput(state, 'seq', inputSeq, bytes.length)
+ }
+
+ /**
+ * Nothing here reached the pty, and `lastInputSeq` is deliberately left where it was. Say what WOULD have been
+ * accepted: a client whose counter has drifted (a frame it dropped on its own side while resyncing, say) can
+ * realign on `expectedSeq` and carry on, instead of having every later keystroke refused too and treating a fine
+ * stream as a dead one.
+ */
+ private refuseInput(state: ActiveStream, reason: 'seq' | 'empty' | 'size', inputSeq: number, size: number): void {
+ // The client numbers what it types next from `expectedSeq`, so keystrokes still held under its old numbering
+ // would land among the new ones: they go, and until the expected one arrives nothing more waits. An oversized
+ // frame refused with a later one held used to release that one after the client's realigned keys (review,
+ // 2026-10-19).
+ this.dropHeldInput(state)
+ state.inputHoldOff = true
+ const expectedSeq = state.lastInputSeq + 1
+ this.sendError(state.connId, 'TERMINAL_INPUT_INVALID', {
+ streamId: state.streamId,
+ reason,
+ expectedSeq,
+ message: reason === 'seq'
+ ? `input seq ${inputSeq} arrived, ${expectedSeq} expected`
+ : reason === 'size' ? `input frame of ${size} bytes exceeds ${INPUT_MAX_BYTES}` : 'empty input frame',
+ })
+ }
+
+ /** The keystrokes that waited for the one just written, as far as they now run on unbroken. */
+ private releaseHeldInput(state: ActiveStream): void {
+ if (state.heldInput.size === 0) return
+ const from = state.lastInputSeq + 1
+ for (let next = from, bytes = state.heldInput.get(next); bytes; next++, bytes = state.heldInput.get(next)) {
+ state.heldInput.delete(next)
+ state.heldInputBytes -= bytes.length
+ this.writeInput(state, next, bytes)
+ }
+ if (state.lastInputSeq >= from) {
+ this.deps.typingTrace?.(`stream=${state.streamId.slice(0, 8)} seq=${from}..${state.lastInputSeq} released after ${Math.round(this.now() - state.heldSince)}ms`)
+ state.heldSince = this.now()
+ }
+ if (state.heldInputTimer) clearTimeout(state.heldInputTimer)
+ // Another gap behind this one gets a full wait of its own.
+ state.heldInputTimer = state.heldInput.size > 0 ? setTimeout(() => this.giveUpHeldInput(state), INPUT_REORDER_WAIT_MS) : null
+ }
+
+ /** The missing keystroke did not come: what waited for it goes, and the client hears once what is expected. */
+ private giveUpHeldInput(state: ActiveStream): void {
+ const waited = [...state.heldInput.keys()]
+ this.dropHeldInput(state)
+ if (state.closing || this.streams.get(state.streamId) !== state) return
+ this.diagnostic(state, 'input_gap_given_up', { expectedSeq: state.lastInputSeq + 1, dropped: waited.length })
+ this.refuseInput(state, 'seq', waited.length > 0 ? Math.min(...waited) : state.lastInputSeq + 1, 0)
+ }
+
+ private dropHeldInput(state: ActiveStream): void {
+ if (state.heldInputTimer) clearTimeout(state.heldInputTimer)
+ state.heldInputTimer = null
+ state.heldInput.clear()
+ state.heldInputBytes = 0
+ }
+
+ private writeInput(state: ActiveStream, inputSeq: number, bytes: Uint8Array): void {
state.lastInputSeq = inputSeq
+ if (this.deps.typingTrace) state.echoProbe = { seq: inputSeq, at: this.now() }
state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
this.tookInput(state, typedByPerson(bytes), nativeSubmitKey(bytes))
// Not awaited. `writeRaw` hands its `send-keys` to the control client's FIFO synchronously, so
@@ -771,7 +880,10 @@ export class TerminalStreamManager {
}
state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
this.tookInput(state, true)
- const result = await state.handle.pasteRaw(text)
+ // Asked again as it lands: a paste takes two tmux processes, and its stream may be closed or taken over
+ // meanwhile (its close does not wait in the input lane the paste holds). Gone, it has nobody to tell.
+ const result = await state.handle.pasteRaw(text, () => !state.closing)
+ if (state.closing) return
if (result.state !== 'succeeded') {
this.sendError(state.connId, 'TERMINAL_PASTE_FAILED', { streamId: state.streamId, message: result.reason })
if (result.dispatch === 'possibly_executed') await this.sendKeyframe(state, 'input')
@@ -829,7 +941,10 @@ export class TerminalStreamManager {
// still needs the image. Hard-failing here used to freeze the whole session over what is, from
// the engine's perspective, just a degraded paste. Fall back to the file's path as ordinary
// text, and keep the file: it has to keep resolving after this call returns.
- const result = await state.handle.pasteRaw(path)
+ // Asked again as it lands: a paste takes two tmux processes, and its stream may be closed or taken over
+ // meanwhile (its close does not wait in the input lane the paste holds). Gone, it has nobody to tell.
+ const result = await state.handle.pasteRaw(path, () => !state.closing)
+ if (state.closing) return
if (result.state !== 'succeeded') {
this.sendError(state.connId, 'TERMINAL_PASTE_IMAGE_FAILED', { streamId: state.streamId, message: result.reason })
if (result.dispatch === 'possibly_executed') await this.sendKeyframe(state, 'input')
@@ -863,7 +978,10 @@ export class TerminalStreamManager {
})
return
}
- const result = await state.handle.pasteRaw(path)
+ // Asked again as it lands: a paste takes two tmux processes, and its stream may be closed or taken over
+ // meanwhile (its close does not wait in the input lane the paste holds). Gone, it has nobody to tell.
+ const result = await state.handle.pasteRaw(path, () => !state.closing)
+ if (state.closing) return
if (result.state !== 'succeeded') {
this.sendError(state.connId, 'TERMINAL_PASTE_FILE_FAILED', { streamId: state.streamId, message: result.reason })
if (result.dispatch === 'possibly_executed') await this.sendKeyframe(state, 'input')
@@ -1113,6 +1231,11 @@ export class TerminalStreamManager {
state.pending.push({ seq, bytes: body.plainBytes })
state.pendingBytes += body.plainBytes
state.outputFrames++
+ const probe = state.echoProbe
+ if (probe) {
+ state.echoProbe = null
+ this.deps.typingTrace?.(`stream=${state.streamId.slice(0, 8)} seq=${probe.seq} first output out +${Math.round(this.now() - probe.at)}ms after it was written`)
+ }
state.outputPlainBytes += body.plainBytes
}
if (state.pendingBytes > PAUSE_HIGH_WATERMARK_BYTES && !state.outputPaused) void this.pauseOutput(state)
@@ -1276,6 +1399,12 @@ export class TerminalStreamManager {
compressedBytes: body.bytes.length,
snapshotMs: Math.max(0, this.now() - startedAt),
})
+ const probe = state.echoProbe
+ if (probe) {
+ this.deps.typingTrace?.(`stream=${state.streamId.slice(0, 8)} seq=${probe.seq} keyframe (${reason}) out +${Math.round(this.now() - probe.at)}ms after it was written`)
+ // Written before the keyframe began, its echo is in it, or in what the keyframe releases next.
+ if (probe.at <= startedAt) state.echoProbe = null
+ }
// The output held behind the keyframe is released as live output, read for an engine's print as it is
// (`repaintBegan`): Codex's clear came in it, after a keyframe taken before its print began, and went straight to
// the viewer while the keyframe was still marked as being taken. The print's keyframe can begin from it here.
@@ -1405,8 +1534,13 @@ export class TerminalStreamManager {
})
if (state.flushTimer) clearTimeout(state.flushTimer)
if (state.stallTimer) clearTimeout(state.stallTimer)
+ if (state.heldInputTimer) clearTimeout(state.heldInputTimer)
state.flushTimer = null
state.stallTimer = null
+ state.heldInputTimer = null
+ // Keystrokes still waiting for a missing one go with the stream: nothing is written to a pane let go.
+ state.heldInput.clear()
+ state.heldInputBytes = 0
this.streams.delete(state.streamId)
const controlled = this.controllerByPlacement.get(state.placementKey) === state.ownerId
if (this.controllerByAgent.get(state.agentId) === state.ownerId) this.controllerByAgent.delete(state.agentId)
diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.ts
index 4c26a6b91..c50572b03 100644
--- a/cli/src/lib/terminalTypes.ts
+++ b/cli/src/lib/terminalTypes.ts
@@ -253,8 +253,10 @@ export interface TerminalStreamHandle<Ref extends TerminalRuntimeRef = TerminalR
endSnapshot(): void
writeRaw(bytes: Uint8Array): Promise<TerminalActionResult>
/** A clipboard paste, delivered as one atomic unit rather than chunked like `writeRaw` — see
- * `pasteRawIntoTmux` for why a paste needs its own path instead of reusing the keystroke one. */
- pasteRaw(text: string): Promise<TerminalActionResult>
+ * `pasteRawIntoTmux` for why a paste needs its own path instead of reusing the keystroke one.
+ * `allowed` is asked again just before the paste lands: a paste takes two tmux processes, and the
+ * stream it was sent on may be closed or taken over meanwhile. */
+ pasteRaw(text: string, allowed?: () => boolean): Promise<TerminalActionResult>
resize(size: TerminalStreamSize): Promise<TerminalActionResult>
/** Scroll a full-screen TUI that owns mouse-tracking but mishandles SGR wheel
* reports (confirmed live for Grok: it echoes the raw escape bytes into its
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index 3b3db1723..4b071a946 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -754,6 +754,34 @@ if [ "$1" = "load-buffer" ]; then cat > /dev/null; fi
}
})
+ it('does not paste a buffer once the paste is no longer allowed, and deletes it', async () => {
+ // Asked again between load-buffer and paste-buffer: the stream the paste came on may have closed meanwhile.
+ const dir = mkdtempSync(join(tmpdir(), 'harness-tmux-allowed-'))
+ const argsFile = join(dir, 'args')
+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh
+printf '%s\\n' "$1" >> "$TMUX_GATE_ARGS"
+if [ "$1" = "load-buffer" ]; then cat > /dev/null; fi
+`)
+ chmodSync(join(dir, 'tmux'), 0o700)
+ writeFileSync(argsFile, '')
+ const previous = { path: process.env.PATH, args: process.env.TMUX_GATE_ARGS }
+ try {
+ process.env.PATH = `${dir}:${previous.path ?? ''}`
+ process.env.TMUX_GATE_ARGS = argsFile
+ assumeTmuxVersion({ major: 3, minor: 7 })
+ const answers = [true, false]
+ expect(await pasteRawIntoTmux('%7', 'clipboard', () => answers.shift() ?? false)).toBe(false)
+ expect(readFileSync(argsFile, 'utf8').trim().split('\n')).toEqual(['load-buffer', 'delete-buffer'])
+ } finally {
+ resetTmuxVersionCache()
+ if (previous.path === undefined) delete process.env.PATH
+ else process.env.PATH = previous.path
+ if (previous.args === undefined) delete process.env.TMUX_GATE_ARGS
+ else process.env.TMUX_GATE_ARGS = previous.args
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+
it('gives up a paste whose tmux never takes its buffer, so the terminals waiting behind it open', async () => {
// A tmux client whose server does not answer waits as long as the server does. Inside the notify room
// that held every terminal open, every session made or killed, and every terminal closed with it.
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 15086e14a..68d913607 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -505,8 +505,8 @@ export function sendLiteralToTmux(pane: string, text: string): Promise<boolean>
* mechanism `sendToTmux` already uses for composer messages — just without the trailing Enter, since a
* paste into a live terminal must not auto-submit.
*/
-export function pasteRawIntoTmux(pane: string, text: string): Promise<boolean> {
- return tmuxPasteText(pane, text, true)
+export function pasteRawIntoTmux(pane: string, text: string, allowed?: () => boolean): Promise<boolean> {
+ return tmuxPasteText(pane, text, true, allowed)
}
export function sendKeyToTmux(pane: string, key: string): Promise<boolean> {
diff --git a/cli/src/lib/tmuxStream.oldTmux.spec.ts b/cli/src/lib/tmuxStream.oldTmux.spec.ts
index d707723de..0ea0fe208 100644
--- a/cli/src/lib/tmuxStream.oldTmux.spec.ts
+++ b/cli/src/lib/tmuxStream.oldTmux.spec.ts
@@ -39,14 +39,17 @@ function controlClient(version: TmuxVersion, meta = '$1|@1|1|80|24|80|24|0|0|0|1
child.kill = () => { child.exitCode = 0; child.emit('close', 0); return true }
child.stdin = new Writable({
write(chunk, _encoding, callback) {
- const line = chunk.toString().replace(/\n$/, '')
- sent.push(line)
- const number = command++
+ // One write may carry several commands (`runTogether`): tmux answers each, in order.
+ const lines = chunk.toString().split('\n').filter((line: string) => line.length > 0)
+ sent.push(...lines)
+ const numbers = lines.map(() => command++)
setImmediate(() => {
callback()
- if (line.startsWith('detach-client')) { child.kill(); return }
- const body = line.startsWith('display-message') ? `${meta}\n` : ''
- child.stdout.emit('data', Buffer.from(`%begin 1 ${number} 0\n${body}%end 1 ${number} 0\n`))
+ lines.forEach((line: string, index: number) => {
+ if (line.startsWith('detach-client')) { child.kill(); return }
+ const body = line.startsWith('display-message') ? `${meta}\n` : ''
+ child.stdout.emit('data', Buffer.from(`%begin 1 ${numbers[index]} 0\n${body}%end 1 ${numbers[index]} 0\n`))
+ })
})
},
})
diff --git a/cli/src/lib/tmuxStream.real.spec.ts b/cli/src/lib/tmuxStream.real.spec.ts
index fb9ee4a8d..62e60df5d 100644
--- a/cli/src/lib/tmuxStream.real.spec.ts
+++ b/cli/src/lib/tmuxStream.real.spec.ts
@@ -254,6 +254,40 @@ run('TmuxControlStream real tmux', () => {
// The stream manager reads the output a keyframe held back as it reads live output, and begins the keyframe for
// Codex's print from it: what follows the clear precedes that keyframe's cut, and must not reach the viewer after it.
+ it('gives a keyframe the cursor of the grid it captured, while the pane is still printing', async () => {
+ // Keys are echoed while their own pane's keyframe is taken (backendSocket.ts `enqueueTerminalBinary`): a
+ // cursor read before the grid, a round trip earlier, sat behind the echo it came with, and the receiver
+ // drew the next one over it.
+ const opened = await TmuxControlStream.open(paneId, { cols: 200, rows: 10 }, { onData: () => {}, onClose: () => {} })
+ expect(opened.state).toBe('succeeded')
+ if (opened.state !== 'succeeded') return
+ try {
+ await opened.value.writeRaw(Buffer.from(`clear; for i in $(seq 1 150); do printf x; sleep 0.005; done; printf '\\nDONE\\n'\r`))
+ await eventually(async () => (await tmux(['capture-pane', '-p', '-t', paneId])).startsWith('xx'))
+ const mismatches: string[] = []
+ let judged = 0
+ for (let attempt = 0; attempt < 20; attempt++) {
+ opened.value.beginSnapshot()
+ const shot = await opened.value.snapshot()
+ opened.value.endSnapshot()
+ expect(shot.state).toBe('succeeded')
+ if (shot.state !== 'succeeded') return
+ const text = Buffer.from(shot.value.bytes).toString('latin1')
+ const cursor = /\u001b\[(\d+);(\d+)H\u001b\[\?7h\u001b\[\?25[hl]$/.exec(text)
+ const firstRow = /\u001b\[1;1H(?:\u001b\[[0-9;]*m)*([^\u001b]*)/.exec(text)?.[1] ?? ''
+ const printed = /^x*/.exec(firstRow)![0].length
+ // Only while the loop is still printing on the first row: once done the prompt moves the cursor on.
+ if (cursor?.[1] !== '1' || printed >= 150) break
+ judged++
+ if (Number(cursor[2]) !== printed + 1) mismatches.push(`grid has ${printed} x, cursor at column ${cursor[2]}`)
+ }
+ expect(judged).toBeGreaterThan(3)
+ expect(mismatches).toEqual([])
+ } finally {
+ await opened.value.close()
+ }
+ })
+
it('holds what is left of the output a snapshot releases behind the next one its sink begins', async () => {
const delivered: string[] = []
let regate: (() => void) | null = null
diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.ts
index 2fb682801..f51a8e6d1 100644
--- a/cli/src/lib/tmuxStream.ts
+++ b/cli/src/lib/tmuxStream.ts
@@ -954,22 +954,35 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
? await this.conversationHistory(plainHistory, historyRange, meta.paneWidth)
: { history: seedsHistory ? (await this.runControlCommand(plainHistory)).stdout : Buffer.alloc(0), rows: null }
let printing = false
- const capture = await this.runControlCommand(baseCapture, () => {
- // `%end` is the ordered cut. Notifications observed before it are
- // represented by capture-pane; only later output may follow the keyframe.
- if (print) printing = printInProgress(this.snapshotPostCut, print)
- this.snapshotPostCut = []
- this.snapshotPostCutBytes = 0
- })
+ // The cursor is read again with the grid, in the same write: tmux answers both before it reads the pane
+ // again (`runTogether`). Taken only from the read above, before the history captures, the cursor of a
+ // pane that printed meanwhile was a step behind the grid it came with — the receiver then drew the next
+ // output at the old place. A keystroke echoed while its own keyframe is taken is exactly that, and its
+ // keyframe no longer holds the keystroke back (backendSocket.ts `enqueueTerminalBinary`).
+ const [screenMetadata, capture] = await Promise.all(this.runControlCommands([
+ { command: `display-message -p -t ${this.runtime.paneId} '${PANE_META_FORMAT}'` },
+ {
+ command: baseCapture,
+ onEnd: () => {
+ // `%end` is the ordered cut. Notifications observed before it are
+ // represented by capture-pane; only later output may follow the keyframe.
+ if (print) printing = printInProgress(this.snapshotPostCut, print)
+ this.snapshotPostCut = []
+ this.snapshotPostCutBytes = 0
+ },
+ },
+ ]))
if (!capture.ok) return { state: 'failed', reason: 'tmux snapshot failed' }
if (printing) return 'printing'
- const bytes = tmuxKeyframe(capture.stdout, meta, history, historyRows, { conversation, tuiOwnsScrollback })
+ const screen = screenMetadata.ok ? parsePaneMeta(screenMetadata.stdout) : null
+ if (!screen || screen.windowPanes !== 1) return { state: 'failed', reason: 'tmux snapshot metadata is invalid' }
+ const bytes = tmuxKeyframe(capture.stdout, screen, history, historyRows, { conversation, tuiOwnsScrollback })
return {
state: 'succeeded',
value: {
bytes,
- cols: meta.paneWidth,
- rows: meta.paneHeight,
+ cols: screen.paneWidth,
+ rows: screen.paneHeight,
},
}
}
@@ -1062,11 +1075,11 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
* keystroke path (chunking there is fine for typing, but reads as several separate pastes to a
* program's own paste-detector once split across multiple `send-keys` commands).
*/
- async pasteRaw(text: string): Promise<TerminalActionResult> {
+ async pasteRaw(text: string, allowed?: () => boolean): Promise<TerminalActionResult> {
if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
if (this.closed) return terminalActionNotStarted('terminal stream is closed')
if (text.length === 0) return TERMINAL_ACTION_SUCCEEDED
- const pasted = await pasteRawIntoTmux(this.runtime.paneId, text)
+ const pasted = await pasteRawIntoTmux(this.runtime.paneId, text, () => !this.closed && (allowed?.() ?? true))
return pasted
? TERMINAL_ACTION_SUCCEEDED
: terminalActionNotStarted('tmux paste-buffer could not be sent')