Fix terminal wait RPC idle timeouts

This commit is contained in:
Jinjing
2026-05-15 19:11:19 -07:00
committed by GitHub
parent f24a968ea0
commit 78fc047646
9 changed files with 462 additions and 23 deletions
@@ -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<Server>()
const sockets = new Set<Socket>()
afterEach(async () => {
for (const socket of sockets) {
socket.destroy()
}
sockets.clear()
await Promise.all(
[...servers].map(
(server) =>
new Promise<void>((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<void>((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 })
})
})
+17 -8
View File
@@ -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
}
+86
View File
@@ -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<ReturnType<typeof createServer>>()
const sockets = new Set<Socket>()
afterEach(async () => {
for (const socket of sockets) {
socket.destroy()
}
sockets.clear()
await Promise.all(
[...servers].map(
(server) =>
new Promise<void>((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<typeof setInterval> | 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<void>((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 }
})
})
})
+38 -2
View File
@@ -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<RuntimeTerminalWait> {
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
+3 -2
View File
@@ -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
})
})
}),
+146
View File
@@ -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()
+11 -9
View File
@@ -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 {
+87 -1
View File
@@ -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<Uint8Array>
@@ -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<void>((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 }
}
+9 -1
View File
@@ -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<TResult>(
})
return
}
if (isKeepaliveFrame(raw)) {
timeout.refresh()
return
}
const parsed = RuntimeRpcEnvelopeSchema.safeParse(raw)
if (!parsed.success || '_keepalive' in parsed.data) {
finish({