mirror of
https://github.com/stablyai/orca.git
synced 2026-09-22 16:02:32 +00:00
* refactor(tests): split oversized test files off the max-lines suppression list Every `*.test.ts`/`*.spec.ts` that carried an `eslint/oxlint-disable max-lines` directive is now split into focused, behavior-scoped suites that fit the 800-line test budget, with shared setup extracted into co-located `*-test-harness.ts` / `*-test-fixtures.ts` modules (300-line budget). 83 files became ~930; the largest output is 797 effective lines. `orca-runtime.test.ts` is intentionally untouched. Test bodies were moved by scripted line-range slicing rather than retyped, so assertions are byte-identical. The only permitted body edits were mechanical rebinding where a shared value moved into a harness (e.g. `tmpHome` -> `homes.tmpHome`). Registries that enumerate test files were updated in lockstep: - config/max-lines-baseline.txt: pruned 341 -> 258 entries (all 83 removed). - config/reliability-gates.jsonc: 33 gates repointed at the split files, with assertionRefs split per file where a gate's coverage now spans several. - .github/workflows/pr.yml: the real-zsh lane now lists the 4 split files that actually exercise zsh, so they keep running in the dedicated shell lane. Also renamed agent-hooks `server-test-fixtures.ts` to `server.test-fixtures.ts` so the global-fetch call-site audit keeps skipping it, and added `.js` extensions to the CLI suites' dynamic harness imports (node16 resolution) to unbreak `build:cli`. Verification: full suite 52,449 passing vs 52,448 at baseline with zero assertions lost; `pnpm lint`, `pnpm typecheck`, and `pnpm build:cli` all exit 0; the terminal-pane e2e spec runs 31/31 headless. * refactor(tests): split hook-idle arbitration suite that oxfmt pushed over budget The pre-commit oxfmt pass reflowed pty-connection-hook-idle-arbitration.test.ts to 811 effective lines, 11 over the test budget. Split the hook-completion side effect and replacement-agent veto cases into their own suite; both files now sit well under the cap and the 15 tests are unchanged. * test: port upstream test changes into the split files after rebase Rebasing onto main surfaced 27 tests that main had added to files this branch deleted, plus edits to tests that had already moved. Taking the deletion side of those modify/delete conflicts would have dropped that coverage silently, so each upstream change is ported into the split file that now owns the behavior — for example main's six orchestration mailbox tests land across orchestration-runs, -send, and -check. Also repoints `orchestration.notification-mailbox-consistency`, a gate main added after this branch's gate remap, at those same three split files, and re-prunes the max-lines baseline against main's (257 entries). Verified: all 27 upstream test titles present; full suite 52,761 passing with the only diff vs baseline being 12 tests main itself removed and 3 that moved from skipped to passing; lint and typecheck exit 0. * fix(test): flush pending continuations before tearing down terminal test globals CI shard 5/16 failed on both Node 24 and 26 with `ReferenceError: window is not defined` from pty-connection.ts, surfacing through pty-connection-daemon-snapshot-replay.test.ts. The reattach/settle chains `await` a real promise and then touch `window.api`. Under fake timers those continuations cannot run, so they only become schedulable once restoreTerminalTestGlobals() switches back to real timers — which previously happened immediately before `delete globalThis.window`, so a late continuation threw and failed the whole file. Flush async ticks in that window instead. This is latent in the source rather than new: the pre-split 25k-line file kept running other tests after these, which gave the chains time to settle before teardown. Splitting the file moved teardown directly behind them. * fix(test): keep an inert window after terminal test teardown instead of deleting it The async-tick flush was not enough: the reattach/settle chain can resolve after teardown regardless of how long we drain, so CI shard 5/16 still failed with `ReferenceError: window is not defined` from pty-connection.ts. A real renderer never loses `window`, so deleting it was the artificial part. Swap in an inert proxy whose properties resolve to callables and whose calls resolve to undefined, making a late `window.api.pty.*` call a harmless no-op. The next test replaces it wholesale via installTerminalTestGlobals(), and no test asserts that `window` is absent.
355 lines
13 KiB
TypeScript
355 lines
13 KiB
TypeScript
import { mkdtempSync } from 'node:fs'
|
|
import { createHash } from 'node:crypto'
|
|
import { tmpdir } from 'node:os'
|
|
import { join } from 'node:path'
|
|
import { describe, expect, it, vi } from 'vitest'
|
|
import { OrcaRuntimeService } from './orca-runtime'
|
|
import { OrchestrationDb } from './orchestration/db'
|
|
import { readRuntimeMetadata } from './runtime-metadata'
|
|
import { OrcaRuntimeRpcServer } from './runtime-rpc'
|
|
import { DeviceRegistry } from './device-registry'
|
|
import { sendRequest, withCurrentOrchestrationContract } from './runtime-rpc-test-harness'
|
|
|
|
vi.mock('../git/worktree', () => {
|
|
const worktrees = [
|
|
{
|
|
path: '/tmp/worktree-a',
|
|
head: 'abc',
|
|
branch: 'feature/foo',
|
|
isBare: false,
|
|
isMainWorktree: false
|
|
}
|
|
]
|
|
return {
|
|
listWorktrees: vi.fn().mockResolvedValue(worktrees),
|
|
listWorktreesStrict: vi.fn().mockResolvedValue(worktrees)
|
|
}
|
|
})
|
|
|
|
describe('OrcaRuntimeRpcServer', () => {
|
|
it('rejects WebSocket requests whose request token differs from the authenticated channel token', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const runtime = {
|
|
getRuntimeId: () => 'test-runtime',
|
|
getStatus: vi.fn().mockResolvedValue({ graphStatus: 'ok' })
|
|
} as unknown as OrcaRuntimeService
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false })
|
|
server['deviceRegistry'] = new DeviceRegistry(userDataPath)
|
|
const channelDevice = server['deviceRegistry']!.addDevice('phone', 'mobile')
|
|
const requestDevice = server['deviceRegistry']!.addDevice('cli', 'runtime')
|
|
const replies: Record<string, unknown>[] = []
|
|
|
|
await server['handleWebSocketMessage'](
|
|
JSON.stringify({
|
|
id: 'req_mismatch',
|
|
method: 'status.get',
|
|
deviceToken: requestDevice.token
|
|
}),
|
|
(response) => replies.push(JSON.parse(response) as Record<string, unknown>),
|
|
() => {},
|
|
undefined,
|
|
undefined,
|
|
channelDevice.token
|
|
)
|
|
|
|
expect(replies).toContainEqual(
|
|
expect.objectContaining({
|
|
id: 'req_mismatch',
|
|
ok: false,
|
|
error: expect.objectContaining({ code: 'unauthorized' })
|
|
})
|
|
)
|
|
})
|
|
|
|
it('isolates mutation replay by the authenticated paired device across reconnects', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const runtime = new OrcaRuntimeService()
|
|
const db = new OrchestrationDb(':memory:')
|
|
runtime.setOrchestrationDb(db)
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false })
|
|
server['deviceRegistry'] = new DeviceRegistry(userDataPath)
|
|
const firstDevice = server['deviceRegistry']!.addDevice('first-cli', 'runtime')
|
|
const secondDevice = server['deviceRegistry']!.addDevice('second-cli', 'runtime')
|
|
|
|
const resetMessages = async (id: string, authenticatedToken: string) => {
|
|
const replies: Record<string, unknown>[] = []
|
|
await server['handleWebSocketMessage'](
|
|
JSON.stringify(
|
|
withCurrentOrchestrationContract({
|
|
id,
|
|
method: 'orchestration.reset',
|
|
orchestrationRequestId: 'paired-reset-request',
|
|
params: { messages: true }
|
|
})
|
|
),
|
|
(response) => replies.push(JSON.parse(response) as Record<string, unknown>),
|
|
() => {},
|
|
undefined,
|
|
undefined,
|
|
authenticatedToken
|
|
)
|
|
return replies[0]
|
|
}
|
|
|
|
try {
|
|
db.insertMessage({ from: 'worker', to: 'coordinator', subject: 'before reset' })
|
|
const first = await resetMessages('reset-first', firstDevice.token)
|
|
db.insertMessage({ from: 'worker', to: 'coordinator', subject: 'after reset' })
|
|
const replay = await resetMessages('reset-replay', firstDevice.token)
|
|
|
|
expect(first).toMatchObject({
|
|
ok: true,
|
|
result: { reset: 'messages', mutation: { replayed: false } }
|
|
})
|
|
expect(replay).toMatchObject({
|
|
ok: true,
|
|
result: { reset: 'messages', mutation: { replayed: true } }
|
|
})
|
|
expect(db.getInbox()).toEqual([expect.objectContaining({ subject: 'after reset' })])
|
|
|
|
const isolated = await resetMessages('reset-second-device', secondDevice.token)
|
|
expect(isolated).toMatchObject({
|
|
ok: true,
|
|
result: { reset: 'messages', mutation: { replayed: false } }
|
|
})
|
|
expect(db.getInbox()).toEqual([])
|
|
} finally {
|
|
db.close()
|
|
await server.stop()
|
|
}
|
|
})
|
|
|
|
it('keeps authenticated paired callers attached to existing federated workers', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const runtime = new OrcaRuntimeService()
|
|
const db = new OrchestrationDb(':memory:')
|
|
runtime.setOrchestrationDb(db)
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false })
|
|
server['deviceRegistry'] = new DeviceRegistry(userDataPath)
|
|
const device = server['deviceRegistry']!.addDevice('existing-cli', 'runtime')
|
|
const existingFingerprint = createHash('sha256').update(device.token).digest('hex')
|
|
db.createRemoteDispatchAttachment({
|
|
dispatchId: 'ctx_existing_remote',
|
|
taskId: 'task_existing_remote',
|
|
homePeerFingerprint: existingFingerprint,
|
|
protocolVersion: 1,
|
|
runtimeEpoch: 'runtime_before_upgrade',
|
|
mutationReceipt: {
|
|
callerFingerprint: existingFingerprint,
|
|
requestId: 'request_existing_remote',
|
|
method: 'orchestration.federationAttachStart',
|
|
payloadHash: 'hash_existing_remote'
|
|
}
|
|
})
|
|
const replies: Record<string, unknown>[] = []
|
|
|
|
try {
|
|
await server['handleWebSocketMessage'](
|
|
JSON.stringify(
|
|
withCurrentOrchestrationContract({
|
|
id: 'show-existing-remote',
|
|
method: 'orchestration.federationShow',
|
|
params: { dispatchId: 'ctx_existing_remote' }
|
|
})
|
|
),
|
|
(response) => replies.push(JSON.parse(response) as Record<string, unknown>),
|
|
() => {},
|
|
undefined,
|
|
undefined,
|
|
device.token
|
|
)
|
|
|
|
expect(replies[0]).toMatchObject({
|
|
ok: true,
|
|
result: { dispatchId: 'ctx_existing_remote', attachment: { state: 'starting' } }
|
|
})
|
|
} finally {
|
|
db.close()
|
|
await server.stop()
|
|
}
|
|
})
|
|
|
|
it('rejects unpaired terminal creates before runtime dispatch', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const createMobileSessionTerminal = vi.fn()
|
|
const runtime = {
|
|
getRuntimeId: () => 'test-runtime',
|
|
createMobileSessionTerminal
|
|
} as unknown as OrcaRuntimeService
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false })
|
|
server['deviceRegistry'] = new DeviceRegistry(userDataPath)
|
|
const replies: Record<string, unknown>[] = []
|
|
const send = async (id: string, deviceToken?: string): Promise<void> => {
|
|
await server['handleWebSocketMessage'](
|
|
JSON.stringify({
|
|
id,
|
|
method: 'session.tabs.createTerminal',
|
|
...(deviceToken ? { deviceToken } : {}),
|
|
params: { worktree: 'id:wt-1' }
|
|
}),
|
|
(response) => replies.push(JSON.parse(response) as Record<string, unknown>),
|
|
() => {}
|
|
)
|
|
}
|
|
|
|
await send('req_missing')
|
|
await send('req_invalid', 'invalid-token')
|
|
|
|
expect(replies).toEqual([
|
|
expect.objectContaining({
|
|
id: 'req_missing',
|
|
error: expect.objectContaining({ code: 'unauthorized' }),
|
|
ok: false
|
|
}),
|
|
expect.objectContaining({
|
|
id: 'req_invalid',
|
|
error: expect.objectContaining({ code: 'unauthorized' }),
|
|
ok: false
|
|
})
|
|
])
|
|
expect(createMobileSessionTerminal).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('allows runtime-scoped WebSocket tokens to use the full RPC surface', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const pushRuntimeGit = vi.fn().mockResolvedValue({ ok: true })
|
|
const runtime = {
|
|
getRuntimeId: () => 'test-runtime',
|
|
pushRuntimeGit
|
|
} as unknown as OrcaRuntimeService
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false })
|
|
server['deviceRegistry'] = new DeviceRegistry(userDataPath)
|
|
const runtimeDevice = server['deviceRegistry']!.addDevice('cli', 'runtime')
|
|
const replies: Record<string, unknown>[] = []
|
|
|
|
await server['handleWebSocketMessage'](
|
|
JSON.stringify({
|
|
id: 'req_push',
|
|
method: 'git.push',
|
|
deviceToken: runtimeDevice.token,
|
|
params: { worktree: 'id:wt-1' }
|
|
}),
|
|
(response) => replies.push(JSON.parse(response) as Record<string, unknown>),
|
|
() => {}
|
|
)
|
|
|
|
expect(replies).toContainEqual(expect.objectContaining({ id: 'req_push', ok: true }))
|
|
expect(pushRuntimeGit).toHaveBeenCalledWith('id:wt-1', undefined, undefined, undefined)
|
|
})
|
|
|
|
it('serves status.get for authenticated callers', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const runtime = new OrcaRuntimeService()
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath })
|
|
|
|
await server.start()
|
|
|
|
const metadata = readRuntimeMetadata(userDataPath)
|
|
const response = await sendRequest(metadata!.transports[0]!.endpoint, {
|
|
id: 'req_1',
|
|
authToken: metadata!.authToken,
|
|
method: 'status.get'
|
|
})
|
|
|
|
expect(response).toMatchObject({
|
|
id: 'req_1',
|
|
ok: true,
|
|
_meta: {
|
|
runtimeId: runtime.getRuntimeId()
|
|
}
|
|
})
|
|
expect((response.result as { graphStatus: string }).graphStatus).toBe('unavailable')
|
|
|
|
await server.stop()
|
|
})
|
|
|
|
it('stamps the authenticated device scope onto status.get for WebSocket clients', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const runtime = new OrcaRuntimeService()
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false })
|
|
server['deviceRegistry'] = new DeviceRegistry(userDataPath)
|
|
const mobile = server['deviceRegistry']!.addDevice('phone', 'mobile')
|
|
const runtimeDevice = server['deviceRegistry']!.addDevice('browser', 'runtime')
|
|
|
|
const sendStatus = async (token: string): Promise<Record<string, unknown>> => {
|
|
const replies: Record<string, unknown>[] = []
|
|
await server['handleWebSocketMessage'](
|
|
JSON.stringify({ id: 'req_status', method: 'status.get', deviceToken: token }),
|
|
(response) => replies.push(JSON.parse(response) as Record<string, unknown>),
|
|
() => {}
|
|
)
|
|
return replies[0]!
|
|
}
|
|
|
|
const mobileReply = await sendStatus(mobile.token)
|
|
expect(mobileReply).toMatchObject({ id: 'req_status', ok: true })
|
|
// Why: the mobile-scope web client reads this to refuse the full app.
|
|
expect((mobileReply.result as { deviceScope?: string }).deviceScope).toBe('mobile')
|
|
|
|
const runtimeReply = await sendStatus(runtimeDevice.token)
|
|
expect((runtimeReply.result as { deviceScope?: string }).deviceScope).toBe('runtime')
|
|
|
|
// Other methods stay unmodified — only status.get carries the scope.
|
|
const replies: Record<string, unknown>[] = []
|
|
await server['handleWebSocketMessage'](
|
|
JSON.stringify({ id: 'req_forbidden', method: 'files.delete', deviceToken: mobile.token }),
|
|
(response) => replies.push(JSON.parse(response) as Record<string, unknown>),
|
|
() => {}
|
|
)
|
|
expect(replies[0]).toMatchObject({
|
|
id: 'req_forbidden',
|
|
ok: false,
|
|
error: { code: 'forbidden' }
|
|
})
|
|
})
|
|
|
|
it('rejects requests with the wrong auth token', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const runtime = new OrcaRuntimeService()
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath })
|
|
|
|
await server.start()
|
|
|
|
const metadata = readRuntimeMetadata(userDataPath)
|
|
const response = await sendRequest(metadata!.transports[0]!.endpoint, {
|
|
id: 'req_1',
|
|
authToken: 'wrong',
|
|
method: 'status.get'
|
|
})
|
|
|
|
expect(response).toMatchObject({
|
|
id: 'req_1',
|
|
ok: false,
|
|
error: {
|
|
code: 'unauthorized'
|
|
}
|
|
})
|
|
|
|
await server.stop()
|
|
})
|
|
|
|
it('rejects malformed requests before dispatch', async () => {
|
|
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
|
const runtime = new OrcaRuntimeService()
|
|
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath })
|
|
|
|
await server.start()
|
|
|
|
const metadata = readRuntimeMetadata(userDataPath)
|
|
const response = await sendRequest(metadata!.transports[0]!.endpoint, {
|
|
authToken: metadata!.authToken,
|
|
method: 'status.get'
|
|
})
|
|
|
|
expect(response).toMatchObject({
|
|
id: 'unknown',
|
|
ok: false,
|
|
error: {
|
|
code: 'bad_request'
|
|
}
|
|
})
|
|
|
|
await server.stop()
|
|
})
|
|
})
|