fix(cli): bound orchestration ask timeouts (#10689)

* fix(cli): bound orchestration ask timeouts

* fix(cli): harden remote timeout boundaries
This commit is contained in:
Jinjing
2026-07-26 12:50:05 -07:00
committed by GitHub
parent 8b25cfc0f8
commit 76b2a3b44d
19 changed files with 765 additions and 268 deletions
@@ -0,0 +1,284 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
const getTerminalHandleMock = vi.hoisted(() => vi.fn())
const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE
const originalPaneKey = process.env.ORCA_PANE_KEY
vi.mock('../format', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { printResult } from '../format'
import { ORCHESTRATION_HANDLERS } from './orchestration'
const invalidTimeoutValues: [string, string | boolean][] = [
['missing', true],
['empty', ''],
['non-numeric', 'not-a-number'],
['zero', '0'],
['negative', '-1'],
['fractional', '1.5'],
['rounded fractional', '9007199254740991.1'],
['unsafe integer', String(Number.MAX_SAFE_INTEGER + 1)]
]
const invokeCheck = (flags: Map<string, string | boolean>) =>
ORCHESTRATION_HANDLERS['orchestration check']({
flags,
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)
const invokeAsk = (flags: Map<string, string | boolean>) =>
ORCHESTRATION_HANDLERS['orchestration ask']({
flags,
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)
beforeEach(() => {
callMock.mockReset()
getTerminalHandleMock.mockReset()
vi.mocked(printResult).mockReset()
delete process.env.ORCA_TERMINAL_HANDLE
delete process.env.ORCA_PANE_KEY
})
afterEach(() => {
if (originalTerminalHandle === undefined) {
delete process.env.ORCA_TERMINAL_HANDLE
} else {
process.env.ORCA_TERMINAL_HANDLE = originalTerminalHandle
}
if (originalPaneKey === undefined) {
delete process.env.ORCA_PANE_KEY
} else {
process.env.ORCA_PANE_KEY = originalPaneKey
}
vi.restoreAllMocks()
})
describe('orchestration timeout flag validation', () => {
it.each(invalidTimeoutValues)('rejects invalid check --timeout-ms: %s', async (_label, value) => {
const flags = new Map<string, string | boolean>([
['wait', true],
['timeout-ms', value]
])
await expect(invokeCheck(flags)).rejects.toThrow(/--timeout-ms/)
expect(callMock).not.toHaveBeenCalled()
expect(getTerminalHandleMock).not.toHaveBeenCalled()
})
it('passes a parsed check timeout and peek mode into the RPC payload', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({ result: { messages: [], count: 0 } })
await invokeCheck(
new Map<string, string | boolean>([
['wait', true],
['peek', true],
['timeout-ms', '250']
])
)
expect(callMock).toHaveBeenCalledWith('orchestration.check', {
terminal: 'term_worker',
unread: false,
peek: true,
all: undefined,
types: undefined,
inject: undefined,
wait: true,
timeoutMs: 250
})
})
it('filters already-read rows from a peek response for pre-peek runtimes', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: {
messages: [
{ id: 'msg_old', from_handle: 'a', subject: 'seen', read: 1 },
{ id: 'msg_new', from_handle: 'a', subject: 'fresh', read: 0 }
],
count: 2,
formatted: 'banners built from all rows'
}
})
await invokeCheck(new Map<string, string | boolean>([['peek', true]]))
const response = vi.mocked(printResult).mock.calls[0]?.[0] as {
result: { messages: { id: string }[]; count: number; formatted?: string }
}
expect(response.result.messages.map((message) => message.id)).toEqual(['msg_new'])
expect(response.result.count).toBe(1)
expect(response.result.formatted).toBeUndefined()
})
it('rejects combined read modes before calling the runtime', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
await expect(
invokeCheck(
new Map<string, string | boolean>([
['unread', true],
['peek', true]
])
)
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('read mode')
})
expect(callMock).not.toHaveBeenCalled()
})
it('warns when a pre-peek runtime returned a full 100-row page', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
const rows = Array.from({ length: 100 }, (_, index) => ({
id: `msg_${index}`,
from_handle: 'a',
subject: `s${index}`,
read: index === 0 ? 0 : 1
}))
callMock.mockResolvedValue({ result: { messages: rows, count: 100 } })
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
await invokeCheck(new Map<string, string | boolean>([['peek', true]]))
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('newest 100 messages'))
})
it('fails --peek --wait against a runtime that returned only read rows', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: {
messages: [{ id: 'msg_old', from_handle: 'a', subject: 'seen', read: 1 }],
count: 1
}
})
await expect(
invokeCheck(
new Map<string, string | boolean>([
['peek', true],
['wait', true]
])
)
).rejects.toMatchObject({ code: 'peek_wait_unsupported' })
})
it.each(invalidTimeoutValues)('rejects invalid ask --timeout-ms: %s', async (_label, value) => {
const flags = new Map<string, string | boolean>([
['to', 'term_coord'],
['question', 'Proceed?'],
['timeout-ms', value]
])
await expect(invokeAsk(flags)).rejects.toThrow(/--timeout-ms/)
expect(callMock).not.toHaveBeenCalled()
expect(getTerminalHandleMock).not.toHaveBeenCalled()
})
it.each([String(2_147_483_647), String(Number.MAX_SAFE_INTEGER)])(
'clamps a safe ask timeout %s before adding transport headroom',
async (rawTimeout) => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false }
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await invokeAsk(
new Map<string, string | boolean>([
['to', 'term_coord'],
['question', 'Proceed?'],
['timeout-ms', rawTimeout]
])
)
expect(callMock).toHaveBeenCalledWith(
'orchestration.ask',
expect.objectContaining({ timeoutMs: 1_800_000 }),
{ timeoutMs: 1_805_000 }
)
}
)
it.each(['+1000', '1000.0', '1e3', '0x3e8'])(
'preserves CLI-compatible exact integer timeout syntax %s',
async (rawTimeout) => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false }
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await invokeAsk(
new Map<string, string | boolean>([
['to', 'term_coord'],
['question', 'Proceed?'],
['timeout-ms', rawTimeout]
])
)
expect(callMock).toHaveBeenCalledWith(
'orchestration.ask',
expect.objectContaining({ timeoutMs: 1_000 }),
{ timeoutMs: 6_000 }
)
}
)
it('keeps an omitted ask timeout out of the payload while using default headroom', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false }
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await invokeAsk(
new Map<string, string | boolean>([
['to', 'term_coord'],
['question', 'Proceed?']
])
)
expect(callMock).toHaveBeenCalledWith(
'orchestration.ask',
expect.objectContaining({ timeoutMs: undefined }),
{ timeoutMs: 605_000 }
)
})
it('uses the parsed ask timeout for both runtime wait and client timeout', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false }
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await invokeAsk(
new Map<string, string | boolean>([
['to', 'term_coord'],
['question', 'Proceed?'],
['timeout-ms', '123']
])
)
expect(callMock).toHaveBeenCalledWith(
'orchestration.ask',
{
to: 'term_coord',
question: 'Proceed?',
options: undefined,
timeoutMs: 123,
from: 'term_worker'
},
{ timeoutMs: 5_123 }
)
})
})
-192
View File
@@ -670,198 +670,6 @@ describe('orchestration task-create caller handle', () => {
})
})
describe('orchestration timeout flag validation', () => {
const invalidTimeoutValues: [string, string | boolean][] = [
['missing', true],
['empty', ''],
['non-numeric', 'not-a-number'],
['zero', '0'],
['negative', '-1']
]
beforeEach(() => {
callMock.mockReset()
delete process.env.ORCA_TERMINAL_HANDLE
delete process.env.ORCA_PANE_KEY
})
const invokeCheck = (flags: Map<string, string | boolean>) =>
ORCHESTRATION_HANDLERS['orchestration check']({
flags,
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)
const invokeAsk = (flags: Map<string, string | boolean>) =>
ORCHESTRATION_HANDLERS['orchestration ask']({
flags,
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)
it.each(invalidTimeoutValues)('rejects invalid check --timeout-ms: %s', async (_label, value) => {
const flags = new Map<string, string | boolean>([
['wait', true],
['timeout-ms', value]
])
await expect(invokeCheck(flags)).rejects.toThrow(/--timeout-ms/)
expect(callMock).not.toHaveBeenCalled()
})
it('passes a parsed check timeout and peek mode into the RPC payload', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({ result: { messages: [], count: 0 } })
await invokeCheck(
new Map<string, string | boolean>([
['wait', true],
['peek', true],
['timeout-ms', '250']
])
)
// Why: --peek rides with unread:false so pre-peek runtimes fall back to
// the non-consuming all mode instead of the destructive mark-read default.
expect(callMock).toHaveBeenCalledWith('orchestration.check', {
terminal: 'term_worker',
unread: false,
peek: true,
all: undefined,
types: undefined,
inject: undefined,
wait: true,
timeoutMs: 250
})
})
it('filters already-read rows from a peek response for pre-peek runtimes', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: {
messages: [
{ id: 'msg_old', from_handle: 'a', subject: 'seen', read: 1 },
{ id: 'msg_new', from_handle: 'a', subject: 'fresh', read: 0 }
],
count: 2,
formatted: 'banners built from all rows'
}
})
vi.mocked(printResult).mockClear()
await invokeCheck(new Map<string, string | boolean>([['peek', true]]))
const response = vi.mocked(printResult).mock.calls[0]?.[0] as {
result: { messages: { id: string }[]; count: number; formatted?: string }
}
expect(response.result.messages.map((m) => m.id)).toEqual(['msg_new'])
expect(response.result.count).toBe(1)
// Why: the pre-peek runtime built `formatted` from all rows, including
// the read one the filter just removed.
expect(response.result.formatted).toBeUndefined()
})
it('rejects combined read modes before calling the runtime', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockClear()
await expect(
invokeCheck(
new Map<string, string | boolean>([
['unread', true],
['peek', true]
])
)
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('read mode')
})
expect(callMock).not.toHaveBeenCalled()
})
it('warns when a pre-peek runtime returned a full 100-row page', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
const rows = Array.from({ length: 100 }, (_, i) => ({
id: `msg_${i}`,
from_handle: 'a',
subject: `s${i}`,
read: i === 0 ? 0 : 1
}))
callMock.mockResolvedValue({ result: { messages: rows, count: 100 } })
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
await invokeCheck(new Map<string, string | boolean>([['peek', true]]))
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('newest 100 messages'))
errorSpy.mockRestore()
})
it('fails --peek --wait against a runtime that returned only read rows', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: {
messages: [{ id: 'msg_old', from_handle: 'a', subject: 'seen', read: 1 }],
count: 1
}
})
await expect(
invokeCheck(
new Map<string, string | boolean>([
['peek', true],
['wait', true]
])
)
).rejects.toMatchObject({ code: 'peek_wait_unsupported' })
})
it.each(invalidTimeoutValues)('rejects invalid ask --timeout-ms: %s', async (_label, value) => {
const flags = new Map<string, string | boolean>([
['to', 'term_coord'],
['question', 'Proceed?'],
['timeout-ms', value]
])
await expect(invokeAsk(flags)).rejects.toThrow(/--timeout-ms/)
expect(callMock).not.toHaveBeenCalled()
})
it('uses the parsed ask timeout for both runtime wait and client timeout', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
callMock.mockResolvedValue({
result: {
answer: 'yes',
messageId: 'msg_1',
threadId: 'thread_1',
timedOut: false
}
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await invokeAsk(
new Map<string, string | boolean>([
['to', 'term_coord'],
['question', 'Proceed?'],
['timeout-ms', '123']
])
)
expect(callMock).toHaveBeenCalledWith(
'orchestration.ask',
{
to: 'term_coord',
question: 'Proceed?',
options: undefined,
timeoutMs: 123,
from: 'term_worker'
},
{ timeoutMs: 5_123 }
)
})
})
describe('orchestration task-list brief output', () => {
it('requests server-side brief and falls back client-side for older runtimes', async () => {
callMock.mockReset().mockResolvedValue({
+11 -6
View File
@@ -8,7 +8,12 @@ import {
} from '../flags'
import { RuntimeClientError } from '../runtime-client'
import { getTerminalHandle } from '../selectors'
import {
clampOrchestrationAskTimeoutMs,
resolveOrchestrationAskClientTimeoutMs
} from '../../shared/orchestration-ask-timeout'
import { abbreviateOrchestrationTasks } from '../../shared/orchestration-task-summary'
import { parsePositiveSafeIntegerText } from '../../shared/timer-delay'
// Why: 15 s is well under Claude Code's ~2 min Bash-tool silence budget while keeping log volume low. See design doc §3.4.
const DEFAULT_KEEPALIVE_INTERVAL_MS = 15_000
@@ -319,11 +324,11 @@ function getOptionalPositiveIntegerValueFlag(
if (typeof raw !== 'string' || raw.length === 0) {
throw new RuntimeClientError('invalid_argument', `Missing value for --${name}.`)
}
const value = Number(raw)
if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
const value = parsePositiveSafeIntegerText(raw)
if (value === null) {
throw new RuntimeClientError(
'invalid_argument',
`Invalid positive integer for --${name}: ${raw}`
`Invalid positive safe integer for --${name}: ${raw}`
)
}
return value
@@ -611,8 +616,8 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
'orchestration ask': async ({ flags, client, cwd, json }) => {
const parsedTimeoutMs = getOptionalPositiveIntegerValueFlag(flags, 'timeout-ms')
const timeoutMs = clampOrchestrationAskTimeoutMs(parsedTimeoutMs)
const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
const timeoutMs = parsedTimeoutMs ?? 600_000
const result = await client.call<{
answer: string | null
messageId: string | null
@@ -625,11 +630,11 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
to: getRequiredStringFlag(flags, 'to'),
question: getRequiredStringFlag(flags, 'question'),
options: getOptionalStringFlag(flags, 'options'),
timeoutMs: parsedTimeoutMs,
timeoutMs: parsedTimeoutMs === undefined ? undefined : timeoutMs,
from
},
// Why: extend past timeoutMs so the RPC transport's 60s default doesn't abort before the runtime's own timeout resolves.
{ timeoutMs: timeoutMs + 5_000 }
{ timeoutMs: resolveOrchestrationAskClientTimeoutMs(parsedTimeoutMs) }
)
// Why: bypass printResult so --json emits a bare JSON object (no envelope) pipeable via `jq -r .answer`, unlike other verbs.
if (json) {
+22
View File
@@ -4,6 +4,7 @@ import { join } from 'node:path'
import { createServer, type Socket } from 'node:net'
import { afterEach, describe, expect, it } from 'vitest'
import type { RuntimeMetadata } from '../../shared/runtime-bootstrap'
import { MAX_TIMER_DELAY_MS } from '../../shared/timer-delay'
import { sendRequest } from './transport'
const servers = new Set<ReturnType<typeof createServer>>()
@@ -25,6 +26,27 @@ afterEach(async () => {
servers.clear()
})
describe('runtime transport timeout validation', () => {
it.each([-1, 1.5, MAX_TIMER_DELAY_MS + 1, Number.MAX_SAFE_INTEGER + 1])(
'rejects invalid timer delay %s before transport discovery',
async (timeoutMs) => {
const metadata: RuntimeMetadata = {
runtimeId: 'runtime-1',
pid: 123,
transports: [],
authToken: 'token',
startedAt: 1
}
await expect(sendRequest(metadata, 'status.get', undefined, timeoutMs)).rejects.toMatchObject(
{
code: 'invalid_argument'
}
)
}
)
})
// 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', () => {
+7
View File
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto'
import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootstrap'
import { isKeepaliveFrame, RuntimeRpcEnvelopeSchema } from './envelope-schema'
import { RuntimeClientError, type RuntimeRpcResponse } from './types'
import { MAX_TIMER_DELAY_MS, isSafeTimerDelayMs } from '../../shared/timer-delay'
export async function sendRequest<TResult>(
metadata: RuntimeMetadata,
@@ -10,6 +11,12 @@ export async function sendRequest<TResult>(
params: unknown,
timeoutMs: number
): Promise<RuntimeRpcResponse<TResult>> {
if (!isSafeTimerDelayMs(timeoutMs)) {
throw new RuntimeClientError(
'invalid_argument',
`Runtime request timeout must be an integer between 0 and ${MAX_TIMER_DELAY_MS}ms.`
)
}
return await new Promise((resolve, reject) => {
const transport = findTransport(metadata, 'unix', 'named-pipe')
if (!transport) {