diff --git a/src/cli/runtime/client-timeout-policy.test.ts b/src/cli/runtime/client-timeout-policy.test.ts new file mode 100644 index 000000000..78816280b --- /dev/null +++ b/src/cli/runtime/client-timeout-policy.test.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { createServer, type Server, type Socket } from 'net' +import { afterEach, describe, expect, it } from 'vitest' +import { RuntimeClient } from './client' + +const servers = new Set() +const sockets = new Set() + +afterEach(async () => { + for (const socket of sockets) { + socket.destroy() + } + sockets.clear() + await Promise.all( + [...servers].map( + (server) => + new Promise((resolve) => { + server.close(() => resolve()) + }) + ) + ) + servers.clear() +}) + +describe.skipIf(process.platform === 'win32')('RuntimeClient timeout policy', () => { + it('does not crash while resolving terminal.wait defaults without params', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-client-')) + const endpoint = join(userDataPath, 'runtime.sock') + const server = createServer((socket) => { + sockets.add(socket) + socket.once('close', () => sockets.delete(socket)) + socket.once('data', (data) => { + const request = JSON.parse(String(data).trim()) as { id: string } + socket.write( + `${JSON.stringify({ + id: request.id, + ok: true, + result: { satisfied: true }, + _meta: { runtimeId: 'runtime-1' } + })}\n` + ) + }) + }) + servers.add(server) + await new Promise((resolve) => server.listen(endpoint, resolve)) + writeFileSync( + join(userDataPath, 'orca-runtime.json'), + JSON.stringify({ + runtimeId: 'runtime-1', + pid: process.pid, + transports: [{ kind: 'unix', endpoint }], + authToken: 'token', + startedAt: Date.now() + }), + 'utf8' + ) + + const client = new RuntimeClient(userDataPath, 100) + const response = await client.call<{ satisfied: boolean }>('terminal.wait') + + expect(response.result).toEqual({ satisfied: true }) + }) +}) diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index ab082aa16..aaff8ec22 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -13,7 +13,7 @@ import { RUNTIME_PROTOCOL_VERSION } from '../../shared/protocol-version' -// Why: for `orchestration.check --wait` the caller's method-level +// Why: for long-poll methods the caller's method-level // `params.timeoutMs` is the inner waiter budget; we extend the client-side // socket timeout to `timeoutMs + GRACE_MS` so the client's own idle timer // never fires before the server-side waiter has had a chance to resolve and @@ -83,15 +83,17 @@ export class RuntimeClient { return response } - // Why: centralises the per-method timeout policy. `orchestration.check` with - // `wait: true` is the only long-poll today, and its inner waiter budget - // lives in `params.timeoutMs`. We widen the client-side socket timeout to - // `timeoutMs + grace` so it doesn't fire before the server has a chance to - // resolve. Without this, a 5 min wait would still die at the 60 s default. + // Why: centralises the per-method timeout policy. Long-poll inner waiter + // budgets live in `params.timeoutMs`; widen the client-side socket timeout + // to `timeoutMs + grace` so it doesn't fire before the server has a chance + // to resolve. Without this, a 5 min wait would still die at the 60 s default. // See design doc §3.1. private resolveMethodTimeoutMs(method: string, params?: unknown): number { - if (method === 'orchestration.check' && isWaitingCheck(params)) { - const inner = Number((params as { timeoutMs?: unknown }).timeoutMs) + if ( + (method === 'orchestration.check' && isWaitingCheck(params)) || + method === 'terminal.wait' + ) { + const inner = Number(getTimeoutMsParam(params)) if (Number.isFinite(inner) && inner > 0) { return Math.max(inner + LONG_POLL_CLIENT_GRACE_MS, this.requestTimeoutMs) } @@ -225,3 +227,10 @@ function isWaitingCheck(params: unknown): boolean { (params as { wait: unknown }).wait === true ) } + +function getTimeoutMsParam(params: unknown): unknown { + if (typeof params !== 'object' || params === null || !('timeoutMs' in params)) { + return undefined + } + return (params as { timeoutMs?: unknown }).timeoutMs +} diff --git a/src/cli/runtime/transport.test.ts b/src/cli/runtime/transport.test.ts new file mode 100644 index 000000000..cd9f369aa --- /dev/null +++ b/src/cli/runtime/transport.test.ts @@ -0,0 +1,86 @@ +import { mkdtempSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { createServer, type Socket } from 'net' +import { afterEach, describe, expect, it } from 'vitest' +import type { RuntimeMetadata } from '../../shared/runtime-bootstrap' +import { sendRequest } from './transport' + +const servers = new Set>() +const sockets = new Set() + +afterEach(async () => { + for (const socket of sockets) { + socket.destroy() + } + sockets.clear() + await Promise.all( + [...servers].map( + (server) => + new Promise((resolve) => { + server.close(() => resolve()) + }) + ) + ) + servers.clear() +}) + +// Why: these tests create Unix domain socket servers in temp directories. +// Windows does not support Unix domain sockets in the same way. +describe.skipIf(process.platform === 'win32')('runtime transport', () => { + it('refreshes the per-call timeout when the runtime sends keepalive frames', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-')) + const endpoint = join(userDataPath, 'runtime.sock') + const server = createServer((socket) => { + sockets.add(socket) + let keepalive: ReturnType | null = null + socket.once('close', () => { + sockets.delete(socket) + if (keepalive) { + clearInterval(keepalive) + } + }) + socket.once('data', (data) => { + const request = JSON.parse(String(data).trim()) as { id: string } + keepalive = setInterval(() => { + socket.write('{"_keepalive":true}\n') + }, 15) + setTimeout(() => { + if (keepalive) { + clearInterval(keepalive) + keepalive = null + } + socket.write( + `${JSON.stringify({ + id: request.id, + ok: true, + result: { satisfied: true }, + _meta: { runtimeId: 'runtime-1' } + })}\n` + ) + }, 90) + }) + }) + servers.add(server) + await new Promise((resolve) => server.listen(endpoint, resolve)) + + const metadata: RuntimeMetadata = { + runtimeId: 'runtime-1', + pid: 123, + transports: [{ kind: 'unix', endpoint }], + authToken: 'token', + startedAt: 1 + } + const response = await sendRequest<{ satisfied: boolean }>( + metadata, + 'terminal.wait', + undefined, + 40 + ) + + expect(response).toMatchObject({ + ok: true, + result: { satisfied: true } + }) + }) +}) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index ccc233fc1..22d771746 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -462,6 +462,7 @@ type TerminalWaiter = { reject: (error: Error) => void timeout: NodeJS.Timeout | null pollInterval: NodeJS.Timeout | null + abortCleanup: (() => void) | null } type MessageWaiter = { @@ -3752,6 +3753,7 @@ export class OrcaRuntimeService { options?: { condition?: RuntimeTerminalWaitCondition timeoutMs?: number + signal?: AbortSignal } ): Promise { const condition = options?.condition ?? 'exit' @@ -3776,7 +3778,12 @@ export class OrcaRuntimeService { resolve, reject, timeout: null, - pollInterval: null + pollInterval: null, + abortCleanup: null + } + if (!this.bindTerminalWaiterAbort(waiter, options?.signal)) { + reject(new Error('request_aborted')) + return } if (effectiveTimeoutMs > 0) { waiter.timeout = setTimeout(() => { @@ -3833,7 +3840,13 @@ export class OrcaRuntimeService { resolve, reject, timeout: null, - pollInterval: null + pollInterval: null, + abortCleanup: null + } + + if (!this.bindTerminalWaiterAbort(waiter, options?.signal)) { + reject(new Error('request_aborted')) + return } if (effectiveTimeoutMs > 0) { @@ -8122,6 +8135,25 @@ export class OrcaRuntimeService { waiter.resolve(result) } + private bindTerminalWaiterAbort( + waiter: TerminalWaiter, + signal: AbortSignal | undefined + ): boolean { + if (!signal) { + return true + } + if (signal.aborted) { + return false + } + const onAbort = (): void => { + this.removeWaiter(waiter) + waiter.reject(new Error('request_aborted')) + } + waiter.abortCleanup = () => signal.removeEventListener('abort', onAbort) + signal.addEventListener('abort', onAbort, { once: true }) + return true + } + private rejectWaitersForHandle(handle: string, code: string): void { const waiters = this.waitersByHandle.get(handle) if (!waiters || waiters.size === 0) { @@ -8146,6 +8178,10 @@ export class OrcaRuntimeService { if (waiter.pollInterval) { clearInterval(waiter.pollInterval) } + if (waiter.abortCleanup) { + waiter.abortCleanup() + waiter.abortCleanup = null + } const waiters = this.waitersByHandle.get(waiter.handle) if (!waiters) { return diff --git a/src/main/runtime/rpc/methods/terminal.ts b/src/main/runtime/rpc/methods/terminal.ts index 81f59d22b..45d144777 100644 --- a/src/main/runtime/rpc/methods/terminal.ts +++ b/src/main/runtime/rpc/methods/terminal.ts @@ -529,10 +529,11 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ defineMethod({ name: 'terminal.wait', params: TerminalWait, - handler: async (params, { runtime }) => ({ + handler: async (params, { runtime, signal }) => ({ wait: await runtime.waitForTerminal(params.terminal, { condition: params.for, - timeoutMs: params.timeoutMs + timeoutMs: params.timeoutMs, + signal }) }) }), diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index a67388bf1..be4a615d3 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -1151,6 +1151,152 @@ describe('OrcaRuntimeRpcServer', () => { } }) + it('emits keepalive frames while terminal.wait blocks and returns its structured timeout', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + const runtime = new OrcaRuntimeService() + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath, + keepaliveIntervalMs: 30 + }) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-1', + worktreeId: 'repo-1::/tmp/worktree-a', + title: 'Terminal 1', + activeLeafId: 'pane:1', + layout: null + } + ], + leaves: [ + { + tabId: 'tab-1', + worktreeId: 'repo-1::/tmp/worktree-a', + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-1' + } + ] + }) + runtime.onPtyData('pty-1', 'Starting MCP servers...\n', 123) + await server.start() + + try { + const metadata = readRuntimeMetadata(userDataPath) + const listResponse = await sendRequest(metadata!.transports[0]!.endpoint, { + id: 'req_list', + authToken: metadata!.authToken, + method: 'terminal.list' + }) + const handle = ( + listResponse.result as { + terminals: { handle: string }[] + } + ).terminals[0]!.handle + + const session = openFramedSession(metadata!.transports[0]!.endpoint, { + id: 'req_terminal_wait', + authToken: metadata!.authToken, + method: 'terminal.wait', + params: { + terminal: handle, + for: 'tui-idle', + timeoutMs: 150 + } + }) + await session.done + + const keepalives = session.frames.filter((f) => f._keepalive === true) + const terminalFrames = session.frames.filter((f) => f.ok !== undefined) + expect(keepalives.length).toBeGreaterThanOrEqual(2) + expect(terminalFrames).toHaveLength(1) + expect(terminalFrames[0]).toMatchObject({ + id: 'req_terminal_wait', + ok: false, + error: { code: 'timeout' } + }) + } finally { + await server.stop() + } + }) + + it('releases terminal.wait long-poll slot when the client closes mid-wait', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + const runtime = new OrcaRuntimeService() + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath, + keepaliveIntervalMs: 1000, + longPollCap: 1 + }) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-1', + worktreeId: 'repo-1::/tmp/worktree-a', + title: 'Terminal 1', + activeLeafId: 'pane:1', + layout: null + } + ], + leaves: [ + { + tabId: 'tab-1', + worktreeId: 'repo-1::/tmp/worktree-a', + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-1' + } + ] + }) + await server.start() + + try { + const metadata = readRuntimeMetadata(userDataPath) + const listResponse = await sendRequest(metadata!.transports[0]!.endpoint, { + id: 'req_list', + authToken: metadata!.authToken, + method: 'terminal.list' + }) + const handle = ( + listResponse.result as { + terminals: { handle: string }[] + } + ).terminals[0]!.handle + const endpoint = metadata!.transports[0]!.endpoint + + const session = openFramedSession(endpoint, { + id: 'req_terminal_wait', + authToken: metadata!.authToken, + method: 'terminal.wait', + params: { terminal: handle, for: 'exit', timeoutMs: 10_000 } + }) + await waitFor(() => server['activeLongPolls'] === 1) + + session.socket.destroy() + await session.done + await waitFor(() => server['activeLongPolls'] === 0) + + const admitted = openFramedSession(endpoint, { + id: 'req_terminal_wait_2', + authToken: metadata!.authToken, + method: 'terminal.wait', + params: { terminal: handle, for: 'tui-idle', timeoutMs: 50 } + }) + await admitted.done + expect(admitted.frames.find((f) => f.ok !== undefined)).toMatchObject({ + id: 'req_terminal_wait_2', + ok: false, + error: { code: 'timeout' } + }) + } finally { + await server.stop() + } + }) + it('releases long-poll slot when client closes mid-wait', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const runtime = new OrcaRuntimeService() diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index f4687e2a9..27aedb513 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -163,17 +163,19 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'worktree.sleep' ]) -// Why: a long-poll request is one whose handler blocks for an unbounded -// amount of time waiting for an external event (today, only -// `orchestration.check` with `wait === true`). This function is the single -// place that classifies it — the long-poll counter, abort wiring, and -// runtime_busy admission check all share this decision. See §3.1. +// Why: a long-poll request is one whose handler blocks waiting for an external +// event. This function is the single place that classifies it — the long-poll +// counter, abort wiring, keepalives, and runtime_busy admission check all +// share this decision. See §3.1. function isLongPollRequest(request: RpcRequest): boolean { - if (request.method !== 'orchestration.check') { - return false + if (request.method === 'terminal.wait') { + return true } - const params = request.params as { wait?: unknown } | undefined - return params?.wait === true + if (request.method === 'orchestration.check') { + const params = request.params as { wait?: unknown } | undefined + return params?.wait === true + } + return false } export class OrcaRuntimeRpcServer { diff --git a/src/shared/remote-runtime-client.test.ts b/src/shared/remote-runtime-client.test.ts index 4d7e2e952..5128094ae 100644 --- a/src/shared/remote-runtime-client.test.ts +++ b/src/shared/remote-runtime-client.test.ts @@ -11,7 +11,7 @@ import { publicKeyFromBase64, publicKeyToBase64 } from './e2ee-crypto' -import { subscribeRemoteRuntimeRequest } from './remote-runtime-client' +import { sendRemoteRuntimeRequest, subscribeRemoteRuntimeRequest } from './remote-runtime-client' const servers: WebSocketServer[] = [] @@ -59,6 +59,24 @@ describe('subscribeRemoteRuntimeRequest', () => { }) }) +describe('sendRemoteRuntimeRequest', () => { + it('refreshes the per-call timeout when the runtime sends keepalive frames', async () => { + const server = await createOneShotServer() + + const response = await sendRemoteRuntimeRequest<{ satisfied: boolean }>( + server.pairing, + 'terminal.wait', + { terminal: 't1', for: 'tui-idle', timeoutMs: 550 }, + 300 + ) + + expect(response).toMatchObject({ + ok: true, + result: { satisfied: true } + }) + }) +}) + async function createSubscriptionServer(): Promise<{ pairing: PairingOffer nextBinary: Promise @@ -138,3 +156,71 @@ async function createSubscriptionServer(): Promise<{ function sendEncrypted(ws: WebSocket, sharedKey: Uint8Array, message: unknown): void { ws.send(encrypt(JSON.stringify(message), sharedKey)) } + +async function createOneShotServer(): Promise<{ pairing: PairingOffer }> { + const serverKeyPair = generateKeyPair() + const wss = new WebSocketServer({ port: 0 }) + servers.push(wss) + + wss.on('connection', (ws) => { + let sharedKey: Uint8Array | null = null + let authenticated = false + + ws.on('message', (data, isBinary) => { + if (isBinary) { + return + } + const frame = data.toString() + if (!sharedKey) { + const hello = JSON.parse(frame) as { publicKeyB64: string } + sharedKey = deriveSharedKey( + serverKeyPair.secretKey, + publicKeyFromBase64(hello.publicKeyB64) + ) + ws.send(JSON.stringify({ type: 'e2ee_ready' })) + return + } + + const plaintext = decrypt(frame, sharedKey) + if (!plaintext) { + return + } + if (!authenticated) { + authenticated = true + sendEncrypted(ws, sharedKey, { type: 'e2ee_authenticated' }) + return + } + + const request = JSON.parse(plaintext) as { id: string } + const key = sharedKey + const keepalive = setInterval(() => { + sendEncrypted(ws, key, { _keepalive: true }) + }, 100) + ws.once('close', () => clearInterval(keepalive)) + setTimeout(() => { + clearInterval(keepalive) + sendEncrypted(ws, key, { + id: request.id, + ok: true, + result: { satisfied: true }, + _meta: { runtimeId: 'runtime-test' } + }) + }, 550) + }) + }) + + await new Promise((resolve) => wss.once('listening', resolve)) + const address = wss.address() as AddressInfo + const pairing = parsePairingCode( + encodePairingOffer({ + v: 2, + endpoint: `ws://127.0.0.1:${address.port}`, + deviceToken: 'device-token', + publicKeyB64: publicKeyToBase64(serverKeyPair.publicKey) + }) + ) + if (!pairing) { + throw new Error('Failed to create test pairing') + } + return { pairing } +} diff --git a/src/shared/remote-runtime-client.ts b/src/shared/remote-runtime-client.ts index 23589deb8..05379f46d 100644 --- a/src/shared/remote-runtime-client.ts +++ b/src/shared/remote-runtime-client.ts @@ -15,7 +15,11 @@ import { publicKeyFromBase64, publicKeyToBase64 } from './e2ee-crypto' -import { RuntimeRpcEnvelopeSchema, type RuntimeRpcResponse } from './runtime-rpc-envelope' +import { + isKeepaliveFrame, + RuntimeRpcEnvelopeSchema, + type RuntimeRpcResponse +} from './runtime-rpc-envelope' type HandshakeState = 'awaiting_ready' | 'awaiting_authenticated' | 'ready' @@ -266,6 +270,10 @@ export async function sendRemoteRuntimeRequest( }) return } + if (isKeepaliveFrame(raw)) { + timeout.refresh() + return + } const parsed = RuntimeRpcEnvelopeSchema.safeParse(raw) if (!parsed.success || '_keepalive' in parsed.data) { finish({