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.

perf: pipeline terminal input writes asynchronously and disable zlib compression for loopback clients

0xken151a979819e8cf
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index feb49c05f..61e195d0a 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -123,7 +123,8 @@ export interface LocalClientSink {
sendBinary: (frame: Uint8Array) => boolean
}
-function isLocalClientId(connId: string): boolean {
+/** A loopback desktop connection (localWsServer.ts), as opposed to a cloud/relay one. */
+export function isLocalClientId(connId: string): boolean {
return connId.startsWith('local:')
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 43d69052d..9756e4555 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -112,7 +112,7 @@ import {
import { readTerminalConfigSnapshot, writeTerminalConfigSnapshot } from './lib/terminalConfigSnapshot.js'
import { Watcher, type LineEvent } from './watcher/watcher.js'
import { chooseHookAgent, startHookServer } from './hookServer.js'
-import { BackendSocket } from './backendSocket.js'
+import { BackendSocket, isLocalClientId } from './backendSocket.js'
import { AutonomousDeviceService } from './lib/autonomous-device/service.js'
import { autonomousDeviceLocalRequest } from './lib/autonomous-device/localApi.js'
import { runAutonomousDeviceCommand } from './lib/autonomous-device/command.js'
@@ -1489,6 +1489,7 @@ async function runForeground(session: AuthSession): Promise<void> {
resolveAgent: (agentId) => registry.resolve(agentId),
sendTarget: (connId, type, payload) => backend.sendTerminalTo(connId, type, payload),
sendBinaryTarget: (connId, frame) => backend.sendTerminalBinaryTo(connId, frame),
+ isLoopback: isLocalClientId,
streamingAvailable: tmuxBackend != null,
diagnostic: (event, fields) => console.log(`[terminal-stream] ${event}`, fields),
})
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index 0806b3752..d83ac1b38 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -2,7 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ENGINES } from '../engines/types.js'
import type { RegisteredSession } from './registry.js'
import { TerminalStreamManager, terminalEngineCapabilities, UPLOAD_CHUNK_BYTES } from './terminalStreamManager.js'
-import { TERMINAL_ACTION_SUCCEEDED, type TerminalStreamHandle, type TerminalStreamSink } from './terminalTypes.js'
+import {
+ TERMINAL_ACTION_SUCCEEDED,
+ terminalActionPossiblyExecuted,
+ type TerminalActionResult,
+ type TerminalStreamHandle,
+ type TerminalStreamSink,
+} from './terminalTypes.js'
import type { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'
import { TerminalBinaryKind, TERMINAL_LOCAL_IMAGE_PASTE_MAX_PAYLOAD_BYTES, type TerminalBinaryClear } from './terminalBinary.js'
import { writeImageToOsClipboard, type OsClipboardImageResult } from './osClipboard.js'
@@ -34,7 +40,14 @@ class FakeStream implements TerminalStreamHandle {
return { state: 'succeeded', value: { bytes: this.snapshotBytes, cols: 120, rows: 40 } }
}
endSnapshot() { this.snapshotEnds++; this.onEndSnapshot?.() }
- async writeRaw(bytes: Uint8Array) { this.writes.push(bytes); return TERMINAL_ACTION_SUCCEEDED }
+ /** When set, every writeRaw parks on it instead of answering at once — a tmux that is slow to `%end`. */
+ pendingWrites: Array<(result: TerminalActionResult) => void> = []
+ holdWrites = false
+ async writeRaw(bytes: Uint8Array): Promise<TerminalActionResult> {
+ this.writes.push(bytes)
+ 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 }
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 }
@@ -59,6 +72,18 @@ describe('TerminalStreamManager', () => {
let manager: TerminalStreamManager
let agents: Map<string, RegisteredSession>
let outputBeforeOpen: Uint8Array | null
+ let terminals: TerminalBackendCoordinator
+
+ const newManager = (extra: { isLoopback?: (connId: string) => boolean } = {}): TerminalStreamManager =>
+ new TerminalStreamManager({
+ terminals,
+ resolveAgent: (id) => agents.get(id),
+ sendTarget: (connId, type, payload) => { sent.push({ connId, type, payload }); return true },
+ sendBinaryTarget: (connId, frame) => { binarySent.push({ connId, frame }); return true },
+ streamingAvailable: true,
+ now: () => Date.now(),
+ ...extra,
+ })
beforeEach(() => {
vi.useFakeTimers()
@@ -68,21 +93,14 @@ describe('TerminalStreamManager', () => {
binarySent = []
outputBeforeOpen = null
agents = new Map([['agent-1', session()]])
- const terminals = {
+ terminals = {
openStream: async (_session: RegisteredSession, _size: unknown, nextSink: TerminalStreamSink) => {
sink = nextSink
if (outputBeforeOpen) nextSink.onData(outputBeforeOpen)
return { state: 'succeeded' as const, value: stream }
},
} as unknown as TerminalBackendCoordinator
- manager = new TerminalStreamManager({
- terminals,
- resolveAgent: (id) => agents.get(id),
- sendTarget: (connId, type, payload) => { sent.push({ connId, type, payload }); return true },
- sendBinaryTarget: (connId, frame) => { binarySent.push({ connId, frame }); return true },
- streamingAvailable: true,
- now: () => Date.now(),
- })
+ manager = newManager()
vi.mocked(writePasteImageFile).mockReset().mockResolvedValue('/fake/paste-images/fake.png')
vi.mocked(writePasteDropFile).mockReset().mockImplementation(async (filename: string) => `/fake/paste-drops/id-${filename}`)
vi.mocked(writeImageToOsClipboard).mockReset().mockResolvedValue({ state: 'written' })
@@ -199,6 +217,65 @@ describe('TerminalStreamManager', () => {
expect(sent.at(-1)?.payload.code).toBe('TERMINAL_SCROLL_INVALID')
})
+ it('pipelines keystrokes to tmux instead of waiting for each %end, and still reports a late failure', async () => {
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-pipeline', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,
+ })
+ const streamId = sent[0].payload.streamId as string
+ stream.holdWrites = true
+
+ const input = (seq: number, text: string): TerminalBinaryClear => ({
+ kind: TerminalBinaryKind.input, streamId, seq, compressed: false, bytes: Buffer.from(text),
+ })
+ // Neither handleBinary resolves against tmux's reply: the second keystroke reaches the control
+ // client while the first is still unanswered. Before, the local socket's dispatch chain sat on
+ // that reply for every character typed.
+ await manager.handleBinary('web-1', input(0, 'a'))
+ await manager.handleBinary('web-1', input(1, 'b'))
+ expect(stream.writes.map((bytes) => Buffer.from(bytes).toString())).toEqual(['a', 'b'])
+ expect(stream.pendingWrites).toHaveLength(2)
+ expect(sent.filter((frame) => frame.type === 'terminal_error')).toHaveLength(0)
+
+ // A reply that arrives after the fact still carries its consequence: an uncertain write gets a
+ // keyframe so the client can see what tmux actually did.
+ const keyframesBefore = binarySent.filter(({ frame }) => frame.kind === TerminalBinaryKind.keyframe).length
+ stream.pendingWrites[0](TERMINAL_ACTION_SUCCEEDED)
+ stream.pendingWrites[1](terminalActionPossiblyExecuted('tmux raw input stopped after a partial write'))
+ await vi.advanceTimersByTimeAsync(50)
+ const errors = sent.filter((frame) => frame.type === 'terminal_error')
+ expect(errors).toHaveLength(1)
+ expect(errors[0].payload).toMatchObject({ code: 'TERMINAL_INPUT_FAILED', streamId })
+ expect(binarySent.filter(({ frame }) => frame.kind === TerminalBinaryKind.keyframe)).toHaveLength(keyframesBefore + 1)
+ })
+
+ it('never compresses output for a loopback client, whatever it asked for', async () => {
+ const big = Buffer.alloc(8 * 1024, 0x61) // well over the 1 KiB floor, and trivially compressible
+
+ await manager.stop()
+ manager = newManager({ isLoopback: (connId) => connId.startsWith('local:') })
+ await manager.handleFrame('local:desktop', 'terminal_open', {
+ requestId: 'open-local', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40, compression: ['zlib', 'none'],
+ })
+ sink!.onData(big)
+ await vi.advanceTimersByTimeAsync(8)
+ const local = binarySent.at(-1)!.frame
+ expect(local.kind).toBe(TerminalBinaryKind.output)
+ expect(local.compressed).toBe(false)
+ expect(local.bytes).toHaveLength(big.length)
+
+ // The same request from anything that is NOT loopback keeps zlib: those frames cross the
+ // internet through the relay, where it still pays.
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-web', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40, compression: ['zlib', 'none'],
+ })
+ sink!.onData(big)
+ await vi.advanceTimersByTimeAsync(8)
+ const remote = binarySent.at(-1)!.frame
+ expect(remote.kind).toBe(TerminalBinaryKind.output)
+ expect(remote.compressed).toBe(true)
+ expect(remote.bytes.length).toBeLessThan(big.length)
+ })
+
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 f438af183..a965ef6ba 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -102,6 +102,8 @@ export interface TerminalStreamManagerDeps {
resolveAgent: (agentId: string) => RegisteredSession | undefined
sendTarget: (connId: string, type: string, payload: FramePayload) => boolean
sendBinaryTarget: (connId: string, frame: TerminalBinaryClear) => boolean
+ /** Whether this connection is the desktop app on THIS computer's loopback (never the cloud). */
+ isLoopback?: (connId: string) => boolean
streamingAvailable: boolean
now?: () => number
diagnostic?: (event: string, fields: Record<string, unknown>) => void
@@ -364,6 +366,12 @@ export class TerminalStreamManager {
this.controllerByPlacement.set(placementKey, connId)
const requestedCompression = Array.isArray(payload.compression) ? payload.compression : []
+ // Never compress for the loopback desktop, whatever it asks for: the bytes cross 127.0.0.1,
+ // and the deflate here plus the inflate on the app's UI thread were a per-frame tax paid on
+ // every TUI redraw for nothing. Decided here rather than in the app because the app cannot
+ // tell this daemon's own machine from one it reaches through the relay — where the same
+ // frames DO cross the internet and zlib still earns its keep.
+ const wantsZlib = requestedCompression.includes('zlib') && !this.deps.isLoopback?.(connId)
state = {
connId,
streamId,
@@ -371,7 +379,7 @@ export class TerminalStreamManager {
engineId: session.engine,
placementKey,
handle: opened.value,
- compression: requestedCompression.includes('zlib') ? 'zlib' : 'none',
+ compression: wantsZlib ? 'zlib' : 'none',
expiresAt: this.now() + HEARTBEAT_TIMEOUT_MS,
lastSyncAt: this.now(),
nextSeq: 0,
@@ -473,11 +481,30 @@ export class TerminalStreamManager {
}
state.lastInputSeq = inputSeq
state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
- const result = await state.handle.writeRaw(bytes)
- if (result.state !== 'succeeded') {
- this.sendError(state.connId, 'TERMINAL_INPUT_FAILED', { streamId: state.streamId, message: result.reason })
- if (result.dispatch === 'possibly_executed') await this.sendKeyframe(state)
- }
+ // Not awaited. `writeRaw` hands its `send-keys` to the control client's FIFO synchronously, so
+ // keystroke order is already fixed by the time it returns its promise — and the seq above is
+ // spent, so the next frame cannot race this one. Awaiting the reply held the whole local
+ // socket (localWsServer.ts serialises every message behind this call) for one tmux round-trip
+ // per keystroke; now the round-trips overlap, which is what ControlCommandQueue pipelines for.
+ // The result still matters, only later: a failure is reported when tmux says so.
+ void state.handle.writeRaw(bytes).then(
+ (result) => {
+ if (state.closing || result.state === 'succeeded') return
+ this.sendError(state.connId, 'TERMINAL_INPUT_FAILED', { streamId: state.streamId, message: result.reason })
+ if (result.dispatch === 'possibly_executed') void this.sendKeyframe(state)
+ },
+ (error: unknown) => {
+ if (state.closing) return
+ this.sendError(state.connId, 'TERMINAL_INPUT_FAILED', {
+ streamId: state.streamId,
+ message: error instanceof Error ? error.message : String(error),
+ })
+ },
+ ).catch((error: unknown) => {
+ // Nothing above is awaited by anyone, so a throw from the reporting itself would otherwise
+ // surface only as a process-level unhandledRejection.
+ this.diagnostic(state, 'input_report_failed', { reason: error instanceof Error ? error.message : String(error) })
+ })
}
private async resize(connId: string, payload: FramePayload): Promise<void> {
diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.ts
index 7352c58dd..5b4b83cf7 100644
--- a/cli/src/lib/tmuxStream.ts
+++ b/cli/src/lib/tmuxStream.ts
@@ -650,6 +650,11 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
* Deliberately NOT wrapped in `serializeOperation`: input must not queue behind a `snapshot()`
* or a `resize()`. Ordering against those still holds because tmux runs control commands in the
* order they were written, which is also what keeps the snapshot's `%end` cut correct.
+ *
+ * ⚠️ Every `runControlCommand` below MUST stay before the first `await`. The caller
+ * (TerminalStreamManager.input) no longer waits for this promise before handing over the next
+ * keystroke, so the order keystrokes reach tmux is the order these calls run synchronously — an
+ * `await` slipped in ahead of them would let a later keystroke overtake an earlier one.
*/
async writeRaw(bytes: Uint8Array): Promise<TerminalActionResult> {
if (this.closed) return terminalActionNotStarted('terminal stream is closed')