refactor(cli): group command handlers and support by feature owner

This commit is contained in:
Neil
2026-11-12 04:17:07 -08:00
parent 61a69df3a6
commit 532304d423
147 changed files with 741 additions and 3037 deletions
+3 -3
View File
@@ -97,9 +97,9 @@ jobs:
src/main/computer/macos-native/macos-native-provider-client.test.ts
src/main/providers/windows-shell-preflight-runtime.windows.test.ts
src/main/computer/desktop-script/actions/desktop-script-provider-actions.test.ts
src/cli/format.test.ts
src/cli/handlers/computer-action-validation.test.ts
src/cli/handlers/computer-state-formatting.test.ts
src/cli/command-result-output.test.ts
src/cli/computer/computer-action-validation.test.ts
src/cli/computer/computer-state-formatting.test.ts
src/cli/index.test.ts
src/cli/runtime/envelope-schema.test.ts
src/shared/remote-runtime/remote-runtime-client.test.ts
+1 -1
View File
@@ -570,7 +570,7 @@
4 test-no-wall-clock:tests/e2e/cross-version-wire/release-checkout.unit.test.ts
2 test-no-wall-clock:tests/e2e/cross-version-wire/release-source-retention.unit.test.ts
1 test-no-wall-clock:tests/e2e/host-cold-park-remote-subscriber.unit.test.ts
1 test-timeout-needs-reason:src/cli/agent-launch-process.test.ts
1 test-timeout-needs-reason:src/cli/agents/agent-launch-process.test.ts
1 test-timeout-needs-reason:src/cli/runtime/serve-pid1-init-reaper.test.ts
1 test-timeout-needs-reason:src/cli/skills-install.test.ts
2 test-timeout-needs-reason:src/main/acp/journal/acp-structured-broken-stream.test.ts
@@ -2,7 +2,7 @@
# Existing production source files importing child_process at runtime outside @orca/process-host.
# Migration debt: this list may only shrink; new callers use the package public API.
src/cli/handlers/core.ts
src/cli/handlers/interactive-login-interruption.ts
src/cli/accounts/interactive-login-interruption.ts
src/cli/runtime/launch.ts
src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts
src/main/ai-vault/scan-service/session-scanner-service-spawn.ts
+7 -11
View File
@@ -10542,7 +10542,7 @@
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
"coveredPlatforms": ["macos"],
"coveredProviders": [],
"coverageNotes": "Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.",
"coverageNotes": "CLI ownership cleanup retires low-value test cases, including explicit-current no-read, legacy success/idempotent acceptance, and caller-pane routing examples. Retained refusal and recovery assertions are listed below; dated receipts keep their original scopes. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.",
"motivatingLinks": [
"https://github.com/stablyai/orca/pull/11107#discussion_r3663321387",
"https://github.com/stablyai/orca/issues/13858",
@@ -10590,12 +10590,10 @@
{
"file": "src/cli/handlers/orchestration-lifecycle-rejection.test.ts",
"assertions": [
"an explicit current worker_done verdict completes without a compatibility read",
"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt",
"legacy succeeded and failed reports require matching terminal Task and Dispatch state",
"a worker_done response without a lifecycle verdict fails closed when authoritative Dispatch and report state cannot confirm settlement",
"stopped or stale Dispatches cannot impersonate report settlement",
"an idempotent retry accepts the first authoritative report from the same worker",
"a Run-home relay rejection reaches the CLI error boundary"
"a Run-home relay rejection reaches the CLI error boundary",
"post-verification failure preserves the worker_done mutation identity for recovery"
]
},
{
@@ -10604,10 +10602,7 @@
},
{
"file": "src/cli/handlers/orchestration-check-identity.test.ts",
"assertions": [
"implicit check carries the caller pane key with a potentially stale environment handle",
"explicit legacy terminal inspection does not inherit the caller pane key"
]
"assertions": ["an empty explicit --terminal is refused before reading a mailbox"]
},
{
"file": "src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts",
@@ -10747,7 +10742,8 @@
"Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. All prior notes and dated/archived evidence retain original scopes.",
"Complete prior commands before federation-lifecycle suite retirement: [\"ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\"pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1\",\"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"]",
"Complete prior testFiles before federation-lifecycle suite retirement: [\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/cli/handlers/orchestration.test.ts\",\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"src/cli/handlers/orchestration-check-identity.test.ts\",\"src/cli/handlers/orchestration-worker-cli.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts\",\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\"]",
"Complete prior assertionRefs before federation-lifecycle suite retirement: [{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"assertions\":[\"replays the coordinator instruction and takes its ack after the app restarts\",\"files loopback mail once under the local Dispatch Run without replacing its owner\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"assertions\":[\"a rejected lifecycle verdict is emitted as a JSON ok=false envelope\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"assertions\":[\"Run delivery resolves through a stable coordinator pane after handle remint\",\"a live handle cannot be retargeted by mismatched pane metadata\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"assertions\":[\"Dispatch delivery resolves through a stable worker pane after handle remint\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"assertions\":[\"a remote worker_done waits for Run-home settlement even when an older CLI omits the wait hint\",\"a current Run home still completes reports from legacy protocol v1/v2 worker servers\",\"persisted protocol v1/v2 workers retain legacy-compatible completion after their worker server updates\",\"preexisting same-outcome terminal ACK batches settle atomically while conflicting outcomes acknowledge nothing\",\"an aborted settlement wait returns operation_unknown instead of accepted success\",\"a Run-home terminal verdict settles the remote attachment and revokes its capability\",\"a terminal verdict cannot settle an unrelated relay item\",\"a terminal verdict cannot contradict the exact queued worker report outcome\",\"a rejected report replays its exact verdict without mutating durable rejection mail twice\"]},{\"file\":\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"assertions\":[\"a v26 database gains a zeroed durable home-to-worker acknowledgment watermark\",\"a complete v26 database starts migration at v26 rather than replaying v7-v26\",\"the migration advances schema version without losing the imported relay cursor\"]},{\"file\":\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"assertions\":[\"worker-start exposes one inactive worker tab before workspace navigation\",\"the coordinator tab remains active\",\"ACK delivery reaches a stable coordinator pane through a stale handle\",\"one spawn remains live with no interruption event\",\"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable\",\"workspace re-entry does not duplicate the worker tab or print Conversation interrupted\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"a compiled CLI worker_done with the wrong identity exits nonzero with ok=false\",\"the exact Task and Dispatch remain dispatched after rejection\",\"the correct worker identity receives an explicit completed lifecycle verdict\",\"an independent runtime read observes the Dispatch completed\"]}]"
"Complete prior assertionRefs before federation-lifecycle suite retirement: [{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"assertions\":[\"replays the coordinator instruction and takes its ack after the app restarts\",\"files loopback mail once under the local Dispatch Run without replacing its owner\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"assertions\":[\"a rejected lifecycle verdict is emitted as a JSON ok=false envelope\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"assertions\":[\"Run delivery resolves through a stable coordinator pane after handle remint\",\"a live handle cannot be retargeted by mismatched pane metadata\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"assertions\":[\"Dispatch delivery resolves through a stable worker pane after handle remint\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"assertions\":[\"a remote worker_done waits for Run-home settlement even when an older CLI omits the wait hint\",\"a current Run home still completes reports from legacy protocol v1/v2 worker servers\",\"persisted protocol v1/v2 workers retain legacy-compatible completion after their worker server updates\",\"preexisting same-outcome terminal ACK batches settle atomically while conflicting outcomes acknowledge nothing\",\"an aborted settlement wait returns operation_unknown instead of accepted success\",\"a Run-home terminal verdict settles the remote attachment and revokes its capability\",\"a terminal verdict cannot settle an unrelated relay item\",\"a terminal verdict cannot contradict the exact queued worker report outcome\",\"a rejected report replays its exact verdict without mutating durable rejection mail twice\"]},{\"file\":\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"assertions\":[\"a v26 database gains a zeroed durable home-to-worker acknowledgment watermark\",\"a complete v26 database starts migration at v26 rather than replaying v7-v26\",\"the migration advances schema version without losing the imported relay cursor\"]},{\"file\":\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"assertions\":[\"worker-start exposes one inactive worker tab before workspace navigation\",\"the coordinator tab remains active\",\"ACK delivery reaches a stable coordinator pane through a stale handle\",\"one spawn remains live with no interruption event\",\"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable\",\"workspace re-entry does not duplicate the worker tab or print Conversation interrupted\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"a compiled CLI worker_done with the wrong identity exits nonzero with ok=false\",\"the exact Task and Dispatch remain dispatched after rejection\",\"the correct worker identity receives an explicit completed lifecycle verdict\",\"an independent runtime read observes the Dispatch completed\"]}]",
"CLI ownership cleanup intentionally removes the retired success, routing and work-count alarms without replacement. Prior CLI assertion references: [{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]}]"
],
"demotionRule": "Keep experimental or demote if either Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if restart or workspace re-entry spawns/resumes/duplicates/interferes with the worker, if retained output becomes unreadable, or if pane-stable delivery reads the wrong mailbox."
},
@@ -1,258 +0,0 @@
#!/usr/bin/env node
// Compare real CLI emits before/after deferring RuntimeClient’s Zod/ws/tweetnacl/store graph until after flag validation.
// Restore seven baseline files; use fresh processes to measure cold graphs, alternate arm order, and verify output/exit equality before timing.
import { execFileSync, spawnSync } from 'node:child_process'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { performance } from 'node:perf_hooks'
import { fileURLToPath } from 'node:url'
const REPO = fileURLToPath(new URL('../../../..', import.meta.url))
const ROUNDS = Number(process.env.ORCA_CLI_DEFER_BENCH_ROUNDS ?? '30')
const WARMUP = Number(process.env.ORCA_CLI_DEFER_BENCH_WARMUP ?? '3')
for (const [name, value] of [
['ORCA_CLI_DEFER_BENCH_ROUNDS', ROUNDS],
['ORCA_CLI_DEFER_BENCH_WARMUP', WARMUP]
]) {
if (!Number.isSafeInteger(value) || value <= 0) {
throw new Error(`${name} must be a positive integer, received ${value}`)
}
}
if (ROUNDS % 2 !== 0) {
// Why: arms alternate which one leads; an odd count biases one arm.
throw new Error(`ORCA_CLI_DEFER_BENCH_ROUNDS must be even, received ${ROUNDS}`)
}
const TOUCHED = [
'src/cli/args.ts',
'src/cli/dispatch.ts',
'src/cli/flags.ts',
'src/cli/format.ts',
'src/cli/index.ts',
'src/cli/runtime/client.ts',
'src/cli/selectors.ts'
]
// Re-read production call forms so reverting deferral cannot make both arms identical; prose mentions must not satisfy the guard.
function assertMarkersFresh() {
const checks = [
['src/cli/index.ts', "await import('./runtime-client.js')"],
['src/cli/index.ts', 'await loadRuntimeClientClass()'],
['src/cli/index.ts', "import type { RuntimeClient } from './runtime-client'"],
['src/cli/runtime/client.ts', "await import('./websocket-transport.js')"],
['src/cli/runtime/client.ts', 'await loadSendWebSocketRequest()'],
['src/cli/args.ts', "import { RuntimeClientError } from './runtime/types'"],
['src/cli/flags.ts', "import { RuntimeClientError } from './runtime/types'"],
['src/cli/dispatch.ts', "import { RuntimeClientError } from './runtime/types'"],
['src/cli/selectors.ts', "import { RuntimeClientError } from './runtime/types'"],
['src/cli/format.ts', "} from './runtime/types'"]
]
for (const [file, marker] of checks) {
if (!readFileSync(join(REPO, file), 'utf8').includes(marker)) {
throw new Error(
`${file} no longer contains \`${marker}\` — cli-runtime-client-deferral-benchmark.mjs is stale`
)
}
}
}
function buildArm(label, baselineRev) {
// Build inside repo so emitted modules resolve its node_modules.
const outDir = join(REPO, `.bench-out-${label}`)
rmSync(outDir, { recursive: true, force: true })
const restore = []
try {
if (baselineRev) {
for (const file of TOUCHED) {
const path = join(REPO, file)
restore.push([path, readFileSync(path)])
writeFileSync(
path,
execFileSync('git', ['show', `${baselineRev}:${file}`], {
cwd: REPO,
maxBuffer: 64 * 1024 * 1024
})
)
}
}
execFileSync(
'npx',
[
'tsc',
'-p',
'config/tsconfig.cli.json',
'--outDir',
outDir,
'--composite',
'false',
'--incremental',
'false'
],
{ cwd: REPO, stdio: 'inherit' }
)
} finally {
for (const [path, contents] of restore) {
writeFileSync(path, contents)
}
}
return join(outDir, 'cli/index.js')
}
function run(entry, argv, env) {
const result = spawnSync(process.execPath, [entry, ...argv], {
cwd: REPO,
env: { ...process.env, ...env },
encoding: 'buffer'
})
if (result.error) {
throw result.error
}
return {
status: result.status,
stdout: result.stdout.toString('utf8'),
stderr: result.stderr.toString('utf8')
}
}
// Count eager CJS graph in a child via Module._load, measuring the graph deferral actually moves.
function countEagerModules(entry) {
const probe = `
const Module = require('module')
const original = Module._load
const seen = new Set()
Module._load = function (request, parent, isMain) {
try { seen.add(Module._resolveFilename(request, parent, isMain)) } catch { seen.add(request) }
return original.apply(this, arguments)
}
require(${JSON.stringify(entry)})
const all = [...seen]
process.stdout.write(JSON.stringify({
total: all.length,
nodeModules: all.filter((p) => p.includes('node_modules')).length
}))
`
const result = spawnSync(process.execPath, ['-e', probe], { cwd: REPO, encoding: 'utf8' })
if (result.status !== 0) {
throw new Error(`module probe failed: ${result.stderr}`)
}
return JSON.parse(result.stdout)
}
const median = (values) => {
const sorted = [...values].sort((a, b) => a - b)
return sorted[Math.floor(sorted.length / 2)]
}
const baselineIndex = process.argv.indexOf('--baseline')
const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1]
assertMarkersFresh()
const userDataPath = mkdtempSync(join(REPO, '.bench-userdata-'))
try {
console.log(`Building eager baseline (${baselineRev}) …`)
const eagerEntry = buildArm('eager', baselineRev)
console.log('Building deferred (working tree) …')
const deferredEntry = buildArm('deferred', null)
const eagerGraph = countEagerModules(eagerEntry)
const deferredGraph = countEagerModules(deferredEntry)
console.log(
`\nEager modules at process load: ${eagerGraph.total} -> ${deferredGraph.total} ` +
`(node_modules ${eagerGraph.nodeModules} -> ${deferredGraph.nodeModules})`
)
if (deferredGraph.total >= eagerGraph.total) {
throw new Error(
'deferred arm loads no fewer modules — the fixture does not exercise the change'
)
}
// Use empty user-data dirs for deterministic runtime-dependent cases.
const isolated = { ORCA_USER_DATA_PATH: userDataPath }
/** @type {Array<[string, string[], Record<string, string>]>} */
const cases = [
['orca --help', ['--help'], {}],
['orca help worktree', ['help', 'worktree'], {}],
['orca (no args)', [], {}],
['unknown command', ['no-such-command'], {}],
['unknown flag', ['worktree', 'list', '--nope'], {}],
['orca agent-context --json', ['agent-context', '--json'], {}],
['orca status --json', ['status', '--json'], isolated],
['orca worktree list --json', ['worktree', 'list', '--json'], isolated]
]
// Compare output/exit before timing or a broken arm printing nothing appears fastest.
for (const [label, argv, env] of cases) {
const before = run(eagerEntry, argv, env)
const after = run(deferredEntry, argv, env)
if (
before.status !== after.status ||
before.stdout !== after.stdout ||
before.stderr !== after.stderr
) {
throw new Error(`arms disagree for "${label}" — refusing to report a timing`)
}
if (before.stdout.length + before.stderr.length === 0) {
throw new Error(`"${label}" produced no output on either arm; it proves nothing`)
}
}
const pad = (value, width) => String(value).padStart(width)
console.log('\nFresh process per sample, wall clock. Lower is better.')
console.log(`rounds=${ROUNDS} warmup=${WARMUP} (per-arm median, arms alternate lead)`)
console.log(`${pad('case', 26)} ${pad('eager', 10)} ${pad('deferred', 10)} ${pad('speedup', 9)}`)
// Accumulated so V8 cannot treat the spawn loop as dead code.
let consumed = 0
for (const [label, argv, env] of cases) {
for (let index = 0; index < WARMUP; index += 1) {
consumed += run(eagerEntry, argv, env).stdout.length
consumed += run(deferredEntry, argv, env).stdout.length
}
const samples = { eager: [], deferred: [] }
for (let round = 0; round < ROUNDS; round += 1) {
// Alternate which arm leads so a drifting machine load cannot be
// attributed to one arm.
const order =
round % 2 === 0
? [
['eager', eagerEntry],
['deferred', deferredEntry]
]
: [
['deferred', deferredEntry],
['eager', eagerEntry]
]
for (const [arm, entry] of order) {
const started = performance.now()
const result = run(entry, argv, env)
samples[arm].push(performance.now() - started)
consumed += result.stdout.length
}
}
const eagerMs = median(samples.eager)
const deferredMs = median(samples.deferred)
console.log(
`${pad(label, 26)} ${pad(`${eagerMs.toFixed(1)} ms`, 10)} ${pad(`${deferredMs.toFixed(1)} ms`, 10)} ${pad(`${(eagerMs / deferredMs).toFixed(2)}x`, 9)}`
)
}
if (consumed === 0) {
throw new Error('no output consumed — the timing loop was optimised away')
}
console.log(
'\nThe help and error rows are the ones the change targets: they return\n' +
'before any client construction, so they drop the whole graph. `status` and\n' +
'`worktree list` still construct a client, so they only save the eager parse\n' +
'of the parts the local path never uses (ws/tweetnacl via websocket-transport).'
)
} finally {
rmSync(userDataPath, { recursive: true, force: true })
for (const label of ['eager', 'deferred']) {
rmSync(join(REPO, `.bench-out-${label}`), { recursive: true, force: true })
}
}
@@ -1,446 +0,0 @@
#!/usr/bin/env node
// Compare stdout/stderr/exit byte-for-byte across two real CLI emits: current tree and selected files restored from baseline (default HEAD~).
// Usage: node config/scripts/cli-runtime-client-deferral-equivalence.mjs [--baseline <rev>]
import { execFileSync, spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const REPO = fileURLToPath(new URL('../../../..', import.meta.url))
// Restore only these baseline files; remove baseline-absent files (e.g. cli-error.ts), then restore the working tree.
const TOUCHED = [
'src/cli/args.ts',
'src/cli/cli-error.ts',
'src/cli/dispatch.ts',
'src/cli/flags.ts',
'src/cli/format.ts',
'src/cli/index.ts',
'src/cli/runtime/client.ts',
'src/cli/selectors.ts'
]
// Fail if real deferral call shapes change or baseline/current could become identical and pass vacuously.
function assertMarkersFresh() {
const index = readFileSync(join(REPO, 'src/cli/index.ts'), 'utf8')
const client = readFileSync(join(REPO, 'src/cli/runtime/client.ts'), 'utf8')
const checks = [
['src/cli/index.ts', index, 'await loadRuntimeClientClass()'],
['src/cli/index.ts', index, "await import('./runtime-client.js')"],
['src/cli/index.ts', index, "import type { RuntimeClient } from './runtime-client'"],
['src/cli/runtime/client.ts', client, 'await loadSendWebSocketRequest()'],
['src/cli/runtime/client.ts', client, "await import('./websocket-transport.js')"]
]
for (const [file, source, marker] of checks) {
// Match calls so prose mentions cannot satisfy the guard.
if (!source.includes(marker)) {
throw new Error(
`${file} no longer contains \`${marker}\` — cli-runtime-client-deferral-equivalence.mjs is stale`
)
}
}
const repointed = ['src/cli/args.ts', 'src/cli/flags.ts', 'src/cli/dispatch.ts']
for (const file of repointed) {
const source = readFileSync(join(REPO, file), 'utf8')
if (!source.includes("import { RuntimeClientError } from './runtime/types'")) {
throw new Error(`${file} no longer repoints RuntimeClientError at ./runtime/types — stale`)
}
}
}
function buildTree(label, baselineRev) {
// Build inside repo so emitted modules resolve its node_modules.
const outDir = join(REPO, `.equiv-out-${label}`)
rmSync(outDir, { recursive: true, force: true })
const restored = []
try {
if (baselineRev) {
for (const file of TOUCHED) {
const path = join(REPO, file)
restored.push([path, existsSync(path) ? readFileSync(path) : null])
const old = spawnSync('git', ['show', `${baselineRev}:${file}`], {
cwd: REPO,
maxBuffer: 64 * 1024 * 1024
})
if (old.status === 0) {
writeFileSync(path, old.stdout)
} else {
rmSync(path, { force: true })
}
}
}
execFileSync(
'npx',
[
'tsc',
'-p',
'config/tsconfig.cli.json',
'--outDir',
outDir,
'--composite',
'false',
'--incremental',
'false'
],
{ cwd: REPO, stdio: 'inherit' }
)
} finally {
for (const [path, contents] of restored) {
if (contents === null) {
rmSync(path, { force: true })
} else {
writeFileSync(path, contents)
}
}
}
return join(outDir, 'cli/index.js')
}
// Every case must exit itself; bound spawnSync so reaching a blocking command fails instead of stalling forever.
const RUN_TIMEOUT_MS = 30_000
function run(entry, argv, env) {
const result = spawnSync(process.execPath, [entry, ...argv], {
cwd: REPO,
env: { ...process.env, ...env },
encoding: 'buffer',
timeout: RUN_TIMEOUT_MS,
killSignal: 'SIGKILL'
})
if (result.error) {
if (result.error.code === 'ETIMEDOUT') {
throw new Error(
`orca ${argv.join(' ')} did not exit within ${RUN_TIMEOUT_MS} ms — it reached a blocking command`
)
}
throw result.error
}
return {
status: result.status,
stdout: result.stdout.toString('utf8'),
stderr: result.stderr.toString('utf8')
}
}
// Require identical bytes; empty user-data dirs make runtime-dependent cases deterministically report not running.
function buildCases(isolatedUserData) {
const isolated = { ORCA_USER_DATA_PATH: isolatedUserData }
const cases = [
// Paths that must never load the runtime client at all.
[[], {}],
[['--help'], {}],
[['help'], {}],
[['help', 'worktree'], {}],
[['help', 'browser'], {}],
[['worktree', '--help'], {}],
[['help', 'no-such-command'], {}],
[['no-such-command'], {}],
[['no-such-command'], { ORCA_PAIRING_CODE: 'garbage' }],
[['wrktree', 'list'], {}],
[['agent-context'], {}],
[['agent-context', '--json'], {}],
// Flag validation must still fire before any runtime lookup.
[['worktree', 'list', '--nonexistent-flag'], {}],
[['worktree', 'list', '--nonexistent-flag', '--json'], {}],
[['browser', 'snapshot', '--nonexistent-flag'], {}],
// resolveRemotePairing throws from the RuntimeClient CONSTRUCTOR.
[['status', '--pairing-code', 'x', '--environment', 'y'], isolated],
[['status', '--pairing-code', 'x', '--environment', 'y', '--json'], isolated],
[['status', '--pairing-code', 'not-a-pairing-code'], isolated],
[['status', '--pairing-code', 'not-a-pairing-code', '--json'], isolated],
[['status', '--pairing-code', 'orca://pair?code=zzzz'], isolated],
[['status', '--environment', 'no-such-environment'], isolated],
[['status', '--environment', 'no-such-environment', '--json'], isolated],
[['worktree', 'list', '--environment', 'no-such-environment', '--json'], isolated],
// The env-var fallback must stay live for non-suppressed commands...
[['status', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }],
[['status', '--json'], { ...isolated, ORCA_REMOTE_PAIRING: 'not-a-pairing-code' }],
[['status', '--json'], { ...isolated, ORCA_ENVIRONMENT: 'no-such-environment' }],
// Keep suppression for local-only groups. Do not invoke agent hooks on/off: they modify real ~/.claude configuration outside ORCA_USER_DATA_PATH.
[['environment', 'list', '--json'], { ...isolated, ORCA_ENVIRONMENT: 'no-such-environment' }],
[['environment', 'list', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }],
[['agent-context', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }],
// Runtime-unavailable reporting (RuntimeClientError formatting).
[['status'], isolated],
[['status', '--json'], isolated],
[['worktree', 'list', '--json'], isolated],
[['terminal', 'list', '--json'], isolated]
]
// Seed fuzzing for reproducibility; all pool tokens must be safe to execute, checked against UNSAFE_TOKENS before running any case.
const tokens = [
'worktree',
'list',
'status',
'browser',
'snapshot',
'terminal',
'environment',
'agent',
'agent-context',
'vm',
'--json',
'--help',
'--pairing-code',
'--environment',
'--worktree',
'orca://pair?code=!!!',
'',
'-',
'--',
'--=',
'a'.repeat(300),
'näme-ünicode',
'💥',
'../..',
'x\ty'
]
let seed = 0x9e3779b9
const next = () => {
seed ^= seed << 13
seed ^= seed >>> 17
seed ^= seed << 5
return (seed >>> 0) / 0x100000000
}
// Check entire pool, not just sampled cases: serve once survived review here and escaped the per-case scan by chance.
assertTokensSafe(tokens, 'fuzz token pool')
assertFuzzPoolDeclaredReadOnly(tokens)
for (let index = 0; index < 400; index += 1) {
const length = 1 + Math.floor(next() * 4)
const argv = []
for (let part = 0; part < length; part += 1) {
argv.push(tokens[Math.floor(next() * tokens.length)])
}
cases.push([argv, isolated])
}
for (const [argv] of cases) {
assertTokensSafe(argv, `argv ${JSON.stringify(argv)}`)
}
return cases
}
// Cases run real CLI with developer HOME/PATH: deny foreground commands, surviving children, config/registry writes and real UI input.
// Deny mixed read/write groups (capture/intercept/label/relation) wholesale; fuzzing cannot distinguish their subcommands.
const FOREGROUND_TOKENS = ['serve', 'open', 'claude-teams', 'exec', 'eval', 'launch', 'attach']
const MUTATING_TOKENS = [
// persistent config and registry state
'on',
'off',
'hooks',
'create',
'remove',
'rm',
'delete',
'add',
'edit',
'set',
'set-value',
'set-base-ref',
'setup-clone',
'setup-create',
'setup-update',
'setup-delete',
'setup-existing-folder',
'install',
'uninstall',
'reinstall',
'update',
'clone',
'apply',
'write',
'reset',
'clear',
'enable',
'disable',
'use-default',
'permissions',
// process and pane lifecycle
'run',
'run-stop',
'start',
'stop',
'kill',
'shutdown',
'close',
'split',
'switch',
'rename',
'focus',
// orchestration writes
'send',
'reply',
'dispatch',
'task-create',
'task-update',
'gate-create',
'gate-resolve',
// issue-tracker writes
'save-issue',
'comment',
'label',
'relation',
'assignee',
'priority',
'estimate',
'due-date',
// browser / computer / emulator input and navigation
'goto',
'back',
'forward',
'reload',
'click',
'dblclick',
'hover',
'fill',
'type',
'type-text',
'select',
'select-all',
'uncheck',
'keypress',
'press-key',
'inserttext',
'hotkey',
'paste-text',
'perform-secondary-action',
'drag',
'scroll',
'scrollintoview',
'wheel',
'move',
'up',
'down',
'tap',
'gesture',
'button',
'rotate',
'upload',
'download',
'dismiss',
'accept',
'highlight',
'viewport',
'geolocation',
'headers',
'credentials',
'offline',
'media',
'device',
'capture',
'intercept'
]
const UNSAFE_TOKENS = new Map([
...FOREGROUND_TOKENS.map((token) => [token, 'runs in the foreground or spawns a process']),
...MUTATING_TOKENS.map((token) => [token, 'can write outside ORCA_USER_DATA_PATH'])
])
// Deny lists miss new verbs (serve once escaped); require explicit read-only allowlisting for every pool token too.
const READ_ONLY_FUZZ_TOKENS = new Set([
// command tokens: every path they can form is a list/show or a parse error
'agent',
'agent-context',
'browser',
'environment',
'list',
'snapshot',
'status',
'terminal',
'vm',
'worktree',
// global flags and hostile strings, which reach no handler at all
'--json',
'--help',
'--pairing-code',
'--environment',
'--worktree',
'orca://pair?code=!!!',
'',
'-',
'--',
'--=',
'a'.repeat(300),
'näme-ünicode',
'💥',
'../..',
'x\ty'
])
function assertTokensSafe(tokens, context) {
for (const token of tokens) {
const reason = UNSAFE_TOKENS.get(token)
if (reason) {
throw new Error(`Refusing to run ${context}: "${token}" ${reason}`)
}
}
}
// Reject neither/both-list membership before any case runs; sampling cannot prove pool safety.
function assertFuzzPoolDeclaredReadOnly(tokens) {
for (const token of tokens) {
if (!READ_ONLY_FUZZ_TOKENS.has(token)) {
throw new Error(
`Fuzz token ${JSON.stringify(token)} is not declared in READ_ONLY_FUZZ_TOKENS — declare it read-only or drop it`
)
}
}
for (const token of READ_ONLY_FUZZ_TOKENS) {
if (UNSAFE_TOKENS.has(token)) {
throw new Error(
`Token ${JSON.stringify(token)} is declared both read-only and unsafe — the two lists disagree`
)
}
}
}
const baselineIndex = process.argv.indexOf('--baseline')
const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1]
assertMarkersFresh()
const isolatedUserData = mkdtempSync(join(REPO, '.equiv-userdata-'))
mkdirSync(join(isolatedUserData, 'empty'), { recursive: true })
let oldEntry
let newEntry
try {
// Build cases and check safety before expensive tsc compiles so unsafe tokens fail immediately.
const cases = buildCases(isolatedUserData)
console.log(`Building baseline (${baselineRev}) …`)
oldEntry = buildTree('old', baselineRev)
console.log('Building working tree …')
newEntry = buildTree('new', null)
console.log(`Comparing ${cases.length} invocations byte for byte …`)
let mismatches = 0
for (const [argv, env] of cases) {
const before = run(oldEntry, argv, env)
const after = run(newEntry, argv, env)
if (
before.status !== after.status ||
before.stdout !== after.stdout ||
before.stderr !== after.stderr
) {
mismatches += 1
console.error(`\nMISMATCH argv=${JSON.stringify(argv)} env=${JSON.stringify(env)}`)
console.error(` exit before=${before.status} after=${after.status}`)
if (before.stdout !== after.stdout) {
console.error(` stdout before=${JSON.stringify(before.stdout.slice(0, 400))}`)
console.error(` after =${JSON.stringify(after.stdout.slice(0, 400))}`)
}
if (before.stderr !== after.stderr) {
console.error(` stderr before=${JSON.stringify(before.stderr.slice(0, 400))}`)
console.error(` after =${JSON.stringify(after.stderr.slice(0, 400))}`)
}
}
}
if (mismatches > 0) {
throw new Error(`${mismatches} of ${cases.length} invocations differ`)
}
console.log(`\nAll ${cases.length} invocations byte-identical (stdout, stderr, exit code).`)
} finally {
rmSync(isolatedUserData, { recursive: true, force: true })
for (const label of ['old', 'new']) {
rmSync(resolve(REPO, `.equiv-out-${label}`), { recursive: true, force: true })
}
}
@@ -9,7 +9,7 @@ import { delimiter, dirname, join, resolve } from 'node:path'
import { runProcess, spawnProcess } from '@orca/process-host'
import { expect, it } from 'vitest'
import { z } from 'zod'
import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../shared/account-runtime-capabilities'
import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities'
const eventSchema = z.object({
name: z.string(),
@@ -1,6 +1,6 @@
import type { HandlerContext } from '../dispatch'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { ANTIGRAVITY_ACCOUNTS_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities'
import type {
AntigravityAccountState,
@@ -12,7 +12,7 @@ import type {
ManagedDataAccountProvider,
ManagedDataAccountsState
} from '../../shared/managed-account-types'
import type { RuntimeStatus } from '../../shared/runtime-types'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import { getWslAccountTarget } from './account-wsl-location'
import {
formatAccountsBlock,
@@ -64,7 +64,7 @@ vi.mock('../../shared/windows-console-input', () => ({
import { ACCOUNT_HANDLERS } from './account'
import { REPEATED_FLAG_SEPARATOR } from '../args'
import type { HandlerContext } from '../dispatch'
import type { RuntimeClient } from '../runtime-client'
import type { RuntimeClient } from '../runtime/client'
import {
ACCOUNT_IMPORT_RUNTIME_CAPABILITY,
ANTIGRAVITY_ACCOUNTS_RUNTIME_CAPABILITY,
@@ -3,8 +3,8 @@ import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { stripElectronRunAsNode } from '../runtime/orca-app-executable'
import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection'
import { buildWslExecArgs, buildWslLoginShellCommand } from '../../shared/wsl-login-shell-command'
@@ -20,7 +20,7 @@ import {
ACCOUNT_IMPORT_RUNTIME_CAPABILITY,
CLAUDE_SIGN_IN_RUNTIME_CAPABILITY
} from '../../shared/account-runtime-capabilities'
import type { RuntimeStatus } from '../../shared/runtime-types'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type {
ClaudeAccountSignIn,
ClaudeRateLimitAccountsState,
@@ -2,9 +2,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { tmpdir } from 'node:os'
import { parseArgs, specPaths } from '../args'
import { parseArgs } from '../args'
import { specPaths } from '../command-spec'
import { ACCOUNT_COMMAND_SPECS } from '../specs/account'
import { RuntimeClient } from '../runtime-client'
import { RuntimeClient } from '../runtime/client'
import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities'
import { addDataAccount } from './data-account-commands'
@@ -3,10 +3,10 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { HandlerContext } from '../dispatch'
import { REPEATED_FLAG_SEPARATOR } from '../args'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities'
import type { RuntimeStatus } from '../../shared/runtime-types'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type {
ManagedDataAccountProvider,
ManagedDataAccountsState
@@ -0,0 +1,64 @@
import { EventEmitter } from 'node:events'
import type { ChildProcess } from 'node:child_process'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { terminateInteractiveLoginProcess } from './interactive-login-interruption'
function loginChild(pid = 4321): ChildProcess & EventEmitter {
return Object.assign(new EventEmitter(), {
kill: vi.fn(),
pid
}) as unknown as ChildProcess & EventEmitter
}
afterEach(() => {
vi.useRealTimers()
})
describe('terminateInteractiveLoginProcess', () => {
it('waits for both Windows tree termination and physical wrapper close', async () => {
const child = loginChild()
let finishTreeKill: (() => void) | undefined
const killWindowsTree = vi.fn(
() =>
new Promise<void>((resolve) => {
finishTreeKill = resolve
})
)
let terminated = false
const pending = terminateInteractiveLoginProcess(child, 'SIGTERM', {
platform: 'win32',
killWindowsTree
}).then(() => {
terminated = true
})
expect(killWindowsTree).toHaveBeenCalledWith(4321)
child.emit('close', 1)
await Promise.resolve()
expect(terminated).toBe(false)
finishTreeKill?.()
await pending
expect(child.kill).not.toHaveBeenCalled()
})
it('forwards the interrupt signal to a direct POSIX child and awaits close', async () => {
const child = loginChild()
let terminated = false
const pending = terminateInteractiveLoginProcess(child, 'SIGHUP', {
platform: 'linux'
}).then(() => {
terminated = true
})
expect(child.kill).toHaveBeenCalledWith('SIGHUP')
await Promise.resolve()
expect(terminated).toBe(false)
child.emit('close', 1)
await pending
expect(child.kill).toHaveBeenCalledOnce()
})
})
@@ -7,7 +7,7 @@ import {
import { inFlightWindowsTreeKill } from '@orca/process-host/windows-tree-kill'
import { createOutputSink } from '@orca/process-host/bounded-output-sink'
import { resolveCliCommand, withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution'
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import {
type InteractiveLoginSession,
LOGIN_PROCESS_POSIX_GRACE_MS,
@@ -1,3 +1,4 @@
import type * as RuntimeMetadata from '../runtime/metadata'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import type * as fs from 'node:fs'
import { tmpdir } from 'node:os'
@@ -46,7 +47,7 @@ const {
getManagedAgentHookStatusesMock: vi.fn()
}))
vi.mock('../runtime-client', () => {
vi.mock('../runtime/client', () => {
class RuntimeClient {
call = callMock
async getOfflineRuntimeAdmission() {
@@ -59,22 +60,14 @@ vi.mock('../runtime-client', () => {
}
}
class RuntimeClientError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
return {
RuntimeClient,
RuntimeClientError,
getDefaultUserDataPath: getDefaultUserDataPathMock
}
return { RuntimeClient }
})
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<typeof RuntimeMetadata>()),
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
vi.mock('../../main/agent-hooks/installation/managed-agent-hook-controls', () => ({
applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock,
getManagedAgentHookStatuses: getManagedAgentHookStatusesMock
@@ -1,13 +1,11 @@
import { join } from 'node:path'
import type { CommandHandler } from '../dispatch'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection'
import {
RuntimeClientError,
type RuntimeClient,
type RuntimeRpcSuccess,
getDefaultUserDataPath
} from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { getDefaultUserDataPath } from '../runtime/metadata'
import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types'
import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../shared/orca-profiles'
import type { GlobalSettings } from '../../shared/global-settings-types'
@@ -10,7 +10,7 @@ import { z } from 'zod'
import {
AGENT_LAUNCH_RUNTIME_CAPABILITIES,
AGENT_LAUNCH_SURFACE_RUNTIME_CAPABILITY
} from '../shared/agent-launch/contracts/agent-launch-runtime-capability'
} from '../../shared/agent-launch/contracts/agent-launch-runtime-capability'
import { agentLaunchFixture } from './agent-launch-test-fixtures'
it('real CLI processes carry surface choices and refuse invalid or unsupported picks before mutation', async () => {
@@ -1,9 +1,9 @@
import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client'
import { classifyAgentLaunchReplayRefusal } from '../shared/agent-launch/contracts/agent-launch-replay-refusal'
import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types'
import { classifyAgentLaunchReplayRefusal } from '../../shared/agent-launch/contracts/agent-launch-replay-refusal'
import {
recoverableOrchestrationArgs,
resolveOrchestrationCliExecutable
} from './runtime/orchestration-recovery-command'
} from '../runtime/orchestration-recovery-command'
/** A lost reply never authorizes a new launch, even on hosts without a replay ledger. */
export async function withCliAgentLaunchRecovery<T>(
@@ -4,31 +4,33 @@ import { randomUUID } from 'node:crypto'
import type {
AgentLaunchPrompt,
AgentLaunchResult
} from '../shared/agent-launch/contracts/agent-launch-intent'
} from '../../shared/agent-launch/contracts/agent-launch-intent'
import {
AGENT_LAUNCH_SURFACES,
type AgentLaunchSurface
} from '../shared/agent-launch/contracts/agent-launch-surface'
import { checkAgentLaunchModelPreferences } from '../shared/agent-launch/choices/agent-launch-model-preferences'
} from '../../shared/agent-launch/contracts/agent-launch-surface'
import { checkAgentLaunchModelPreferences } from '../../shared/agent-launch/choices/agent-launch-model-preferences'
import {
AGENT_LAUNCH_RUNTIME_CAPABILITY,
AGENT_LAUNCH_PROMPT_CARRY_RUNTIME_CAPABILITY,
AGENT_LAUNCH_LOCAL_PRESENTATION_RUNTIME_CAPABILITY,
AGENT_LAUNCH_REPLAY_REQUIRED_RUNTIME_CAPABILITY,
AGENT_LAUNCH_SURFACE_RUNTIME_CAPABILITY
} from '../shared/agent-launch/contracts/agent-launch-runtime-capability'
import { createStructuredAgentSessionOperationId } from '../shared/agent-session/lifecycle/structured-agent-session-mutation'
import { parseAgentSessionOperationTimestamp } from '../shared/agent-session/agent-session-host-authority'
import type { RuntimeStatus } from '../shared/runtime-types'
import type { TuiAgent } from '../shared/agent-launch/catalog/tui-agent'
import { isTuiAgent } from '../shared/agent-launch/catalog/tui-agent-config'
} from '../../shared/agent-launch/contracts/agent-launch-runtime-capability'
import { createStructuredAgentSessionOperationId } from '../../shared/agent-session/lifecycle/structured-agent-session-mutation'
import { parseAgentSessionOperationTimestamp } from '../../shared/agent-session/agent-session-host-authority'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent'
import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config'
import {
getOptionalStringFlag,
getRequiredStringFlag,
getRequiredStringFlagAllowingEmpty,
rejectValuelessFlag
} from './flags'
import { RuntimeClientError, type RuntimeClient, type RuntimeRpcSuccess } from './runtime-client'
} from '../flags'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { withCliAgentLaunchRecovery } from './agent-launch-recovery'
type Flags = Map<string, string | boolean>
@@ -1,5 +1,5 @@
import { AGENT_LAUNCH_RUNTIME_CAPABILITIES } from '../shared/agent-launch/contracts/agent-launch-runtime-capability'
import { okFixture } from './test-fixtures'
import { AGENT_LAUNCH_RUNTIME_CAPABILITIES } from '../../shared/agent-launch/contracts/agent-launch-runtime-capability'
import { okFixture } from '../test-fixtures'
export function agentLaunchHostFixture() {
return okFixture('req_status', { capabilities: [...AGENT_LAUNCH_RUNTIME_CAPABILITIES] })
@@ -5,10 +5,10 @@ import {
getAgentLaunchCapabilities,
parseCliAgent,
readCliAgentLaunch
} from '../agent-launch-request'
} from './agent-launch-request'
import { getRequiredStringFlag } from '../flags'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { getRequiredWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors'
export const AGENT_LAUNCH_HANDLERS: Record<string, CommandHandler> = {
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient } from '../runtime-client'
import { RuntimeClient } from '../runtime/client'
import { CHAT_HANDLERS } from './chat'
function chatClient(isRemote: boolean): { client: RuntimeClient; call: ReturnType<typeof vi.fn> } {
@@ -1,7 +1,7 @@
import type { CommandHandler } from '../dispatch'
import { getPresentStringFlag, getRequiredStringFlag } from '../flags'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env'
type ChatRenameResult = { name: string | null; applied: boolean }
@@ -1,4 +1,4 @@
import type { ArtifactListItem, ArtifactListPage } from '../shared/artifacts/artifacts'
import type { ArtifactListItem, ArtifactListPage } from '../../shared/artifacts/artifacts'
export function formatArtifactList(artifacts: readonly ArtifactListItem[]): string {
if (artifacts.length === 0) {
@@ -19,9 +19,9 @@ import {
} from '../../shared/artifacts/artifact-sharing-gate'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection'
import { RuntimeClientError } from '../runtime-client'
import { formatArtifactListPage, formatArtifactShared } from '../artifact-format'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime/types'
import { formatArtifactListPage, formatArtifactShared } from './artifact-format'
import { printResult } from '../command-result-output'
function stringFlag(ctx: HandlerContext, name: string): string | undefined {
const value = ctx.flags.get(name)
@@ -3,16 +3,16 @@
import {
AUTOMATION_OWNER_CONFLICT_CODES,
AutomationOwnerConflictError
} from '../shared/automations/ownership/automation-owner-conflict'
import type { AutomationDestination } from '../shared/automations/ownership/automation-owner-precondition'
import type { RuntimeWorktreeRecord } from '../shared/runtime-types'
import type { SshTargetSummary } from '../shared/ssh-types'
import type { Repo } from '../shared/repo-types'
import { getRepoRoutingConnectionId } from '../shared/execution-host'
import { getManagedOrcadSshTargetId } from '../shared/execution-host/managed-orcad-execution-host'
import { listEnvironments } from '../shared/remote-runtime/host-store/runtime-environment-store'
import { RuntimeClient } from './runtime-client'
import { fetchSshTargetSummaries } from './host-selector-alternatives'
} from '../../shared/automations/ownership/automation-owner-conflict'
import type { AutomationDestination } from '../../shared/automations/ownership/automation-owner-precondition'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts'
import type { SshTargetSummary } from '../../shared/ssh-types'
import type { Repo } from '../../shared/repo-types'
import { getRepoRoutingConnectionId } from '../../shared/execution-host'
import { getManagedOrcadSshTargetId } from '../../shared/execution-host/managed-orcad-execution-host'
import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store'
import { RuntimeClient } from '../runtime/client'
import { fetchSshTargetSummaries } from '../host-selector-alternatives'
/** Empty selectors mean the execution host cannot change. */
export type AutomationDestinationTarget = { repo?: string; workspace?: string }
@@ -1,4 +1,4 @@
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
/** An explicit empty value clears saved extras. */
export function getExtraAgentArgsFlag(flags: Map<string, string | boolean>): string | undefined {
@@ -1,13 +1,13 @@
// Use authority-projected owners: stored target fields survive host removal and re-registration.
import type { Automation } from '../shared/automations/automation-definition'
import type { AutomationRun } from '../shared/automations/history/automation-run'
import type { AutomationListItem } from '../shared/automations/ownership/automation-list-scope'
import type { AutomationOwnerPrecondition } from '../shared/automations/ownership/automation-owner-precondition'
import { getAutomationLegacyRepoId } from '../shared/automations/history/automation-run-identity'
import { formatAutomationPrecheckTimeout } from '../shared/automations/launch/automation-precheck'
import { formatAutomationSchedule } from '../shared/automations/scheduling/automation-schedules'
import { quoteCliCommandArgument } from './shell-command-quote'
import type { Automation } from '../../shared/automations/automation-definition'
import type { AutomationRun } from '../../shared/automations/history/automation-run'
import type { AutomationListItem } from '../../shared/automations/ownership/automation-list-scope'
import type { AutomationOwnerPrecondition } from '../../shared/automations/ownership/automation-owner-precondition'
import { getAutomationLegacyRepoId } from '../../shared/automations/history/automation-run-identity'
import { formatAutomationPrecheckTimeout } from '../../shared/automations/launch/automation-precheck'
import { formatAutomationSchedule } from '../../shared/automations/scheduling/automation-schedules'
import { quoteCliCommandArgument } from '../shell-command-quote'
export type AutomationListPayload = {
automations: Automation[]
@@ -19,7 +19,7 @@ import {
getOptionalStringFlag,
getRequiredStringFlag
} from '../flags'
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
const PRESET_TRIGGERS = new Set<AutomationSchedulePreset>(['hourly', 'daily', 'weekdays', 'weekly'])
const SCHEDULE_MODIFIER_FLAGS = ['day', 'time'] as const
@@ -6,9 +6,9 @@ import {
EXTRA_AGENT_ARGS_HOST_UPDATE_REQUIRED,
hasExtraAgentArgs
} from '../../shared/agent-launch/startup/automation-extra-agent-args'
import type { RuntimeStatus } from '../../shared/runtime-types'
import type { RuntimeClient } from '../runtime-client'
import { RuntimeClientError } from '../runtime-client'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
const SETUP_CHOICE_HOST_UPDATE_REQUIRED =
"This host's Orca is too old for --setup on automations. Update Orca on that host, or run the command without --setup."
@@ -3,7 +3,7 @@
import {
AUTOMATION_OWNER_CONFLICT_CODES,
isAutomationOwnerConflictCode
} from '../shared/automations/ownership/automation-owner-conflict'
} from '../../shared/automations/ownership/automation-owner-conflict'
export type AutomationOwnerConflictRecovery = { nextSteps: readonly string[] }
@@ -1,6 +1,7 @@
import type { AutomationRun } from '../shared/automations/history/automation-run'
import type { RuntimeRpcSuccess } from '../shared/runtime-rpc-envelope'
import { RuntimeClientError, type RuntimeClient } from './runtime-client'
import type { AutomationRun } from '../../shared/automations/history/automation-run'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
// Keep typical snapshot pages below the remote reply limit; retry smaller when needed.
export const AUTOMATION_RUNS_PAGE_SIZE = 25
@@ -1,4 +1,4 @@
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import type { AutomationWorkspaceMode } from '../../shared/automations/automation-definition'
export function getAutomationSetupFlag(
@@ -18,22 +18,22 @@ import {
formatAutomationRuns,
formatAutomationRunsPage,
formatAutomationShow,
printResult,
type AutomationShowPayload
} from '../format'
} from './automation-format'
import { printResult } from '../command-result-output'
import {
getOptionalPositiveIntegerFlag,
getOptionalStringFlag,
getRequiredStringFlag
} from '../flags'
import { resolveAutomationDestination, routeAutomationCreate } from '../automation-destination'
import { resolveAutomationDestination, routeAutomationCreate } from './automation-destination'
import {
AUTOMATION_RUNS_PAGE_SIZE,
automationRunsRpc,
readAllAutomationRuns,
readAutomationRunsPage
} from '../automation-runs-paging'
import { RuntimeClientError } from '../runtime-client'
} from './automation-runs-paging'
import { RuntimeClientError } from '../runtime/types'
import { getOptionalWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors'
import {
assertWorkspaceTargetFlagsCompatible,
+1 -1
View File
@@ -8,7 +8,7 @@ import type {
BrowserNetworkLogResult
} from '../../shared/browser/runtime/runtime-browser-contracts'
import type { CommandHandler } from '../dispatch'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../flags'
import { getBrowserCommandTarget } from './browser-command-target'
+1 -1
View File
@@ -4,7 +4,7 @@ import type {
BrowserCookieSetResult
} from '../../shared/browser/runtime/runtime-browser-contracts'
import type { CommandHandler } from '../dispatch'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import {
getOptionalStringFlag,
getRequiredStringFlag,
+1 -1
View File
@@ -3,7 +3,7 @@ import type {
BrowserViewportResult
} from '../../shared/browser/runtime/runtime-browser-contracts'
import type { CommandHandler } from '../dispatch'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import {
getOptionalStringFlag,
getRequiredFiniteNumber,
+1 -1
View File
@@ -4,7 +4,7 @@ import type {
} from '../../shared/browser/extensions/browser-extension-types'
import type { CommandHandler } from '../dispatch'
import { getPresentStringFlag } from '../flags'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { resolveRepoPathArgument } from '../repo-path-arguments'
export const BROWSER_EXTENSION_HANDLERS: Record<string, CommandHandler> = {
+1 -1
View File
@@ -7,7 +7,7 @@ import { BROWSER_IDENTITY_RUNTIME_CAPABILITY } from '../../shared/browser/runtim
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { getRequiredStringFlag } from '../flags'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
async function assertBrowserIdentitySupported({ client }: HandlerContext): Promise<void> {
+1 -1
View File
@@ -14,7 +14,7 @@ import type {
} from '../../shared/browser/runtime/runtime-browser-contracts'
import type { CommandHandler } from '../dispatch'
import { resolveRepoPathArgument } from '../repo-path-arguments'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import {
getOptionalNumberFlag,
getOptionalStringFlag,
+1 -1
View File
@@ -12,7 +12,7 @@ import type {
} from '../../shared/browser/runtime/runtime-browser-contracts'
import type { CommandHandler } from '../dispatch'
import { formatScreenshot, formatSnapshot, saveBrowserScreenshot } from './browser-format'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import {
getOptionalPositiveIntegerFlag,
getOptionalStringFlag,
+1 -1
View File
@@ -13,7 +13,7 @@ import {
formatTabProfileClone,
formatTabProfileShow
} from './browser-format'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { getBrowserCommandTarget } from './browser-command-target'
+1 -1
View File
@@ -1,5 +1,5 @@
import type { CommandHandler } from '../dispatch'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { getRequiredStringFlag, getRequiredStringFlagAllowingEmpty } from '../flags'
import { getBrowserCommandTarget } from './browser-command-target'
+1 -1
View File
@@ -12,7 +12,7 @@ import {
formatTabListWithProfiles,
formatTabShow
} from './browser-format'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import {
getOptionalNonNegativeIntegerFlag,
getOptionalStringFlag,
+1 -1
View File
@@ -3,7 +3,7 @@ import {
matchAutomationOwnerConflict,
stripAutomationOwnerConflictCode
} from '../shared/automations/ownership/automation-owner-conflict'
import { automationOwnerConflictRecovery } from './automation-owner-conflict-recovery'
import { automationOwnerConflictRecovery } from './automations/automation-owner-conflict-recovery'
import { worktreeSelectorRecovery } from './worktree-selector-recovery'
import { ambiguousWorkspaceChoices, selectorAmbiguityRecovery } from './selector-ambiguity-recovery'
import type { RuntimeRpcFailure } from './runtime-client'
@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { printResult } from './format'
import { printResult } from './command-result-output'
let testScreenshotDir: string | null = null
+15
View File
@@ -0,0 +1,15 @@
import { formatBrowserActionEffects } from './browser/browser-format'
import { prepareComputerCliJsonResult } from './computer/computer-format'
import type { RuntimeRpcSuccess } from '../shared/runtime-rpc-envelope'
export function printResult<TResult>(
response: RuntimeRpcSuccess<TResult>,
json: boolean,
formatter: (value: TResult) => string
): void {
if (json) {
console.log(JSON.stringify(prepareComputerCliJsonResult(response), null, 2))
return
}
console.log(formatter(response.result) + formatBrowserActionEffects(response.result))
}
@@ -1,4 +1,4 @@
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
export function validateExclusiveWindowTarget(
windowId: number | undefined,
@@ -11,7 +11,7 @@ import {
getRequiredStringFlag,
getRequiredStringFlagAllowingEmpty
} from '../flags'
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import {
validateDragTarget,
validateElementOrCoordinates,
@@ -2,20 +2,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime-client', async () => {
vi.mock('../runtime/client', async () => {
class RuntimeClient {
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
}
// Error formatting uses instanceof, so preserve the production error classes.
const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js')
return { RuntimeClient, RuntimeClientError, RuntimeRpcFailureError }
return { RuntimeClient }
})
import { main } from '../index'
import { okFixture, queueFixtures } from '../test-fixtures'
describe('orca computer action CLI validation', () => {
beforeEach(() => {
@@ -86,55 +82,6 @@ describe('orca computer action CLI validation', () => {
expect(process.exitCode).toBe(1)
})
it('allows literal plus as a press-key key', async () => {
queueFixtures(
callMock,
okFixture('req_press_key', {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', id: 1, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 1,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'synthetic',
actionName: 'pressKey',
verification: { state: 'unverified', reason: 'synthetic_input' }
}
})
)
await main(
[
'computer',
'press-key',
'--session',
'manual',
'--app',
'Finder',
'--key',
'+',
'--no-screenshot'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.pressKey', {
session: 'manual',
app: 'Finder',
key: '+',
noScreenshot: true,
treeDiff: true
})
expect(vi.mocked(console.error)).not.toHaveBeenCalled()
expect(process.exitCode).toBeUndefined()
})
it('rejects conflicting get-app-state window target flags before calling the runtime', async () => {
await main(
[
@@ -199,61 +146,6 @@ describe('orca computer action CLI validation', () => {
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Missing text from stdin')
expect(process.exitCode).toBe(1)
})
it('allows empty stdin for set-value so fields can be cleared', async () => {
queueFixtures(
callMock,
okFixture('req_set_value', {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', id: 1, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 1,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'accessibility',
actionName: 'setValue',
verification: { state: 'verified', property: 'value' }
}
})
)
const stdin = mockStdin(false, [])
try {
await main(
[
'computer',
'set-value',
'--session',
'manual',
'--app',
'Finder',
'--element-index',
'1',
'--value-stdin',
'--no-screenshot'
],
'/tmp/repo/src'
)
} finally {
stdin.restore()
}
expect(callMock).toHaveBeenCalledWith('computer.setValue', {
session: 'manual',
app: 'Finder',
elementIndex: 1,
value: '',
noScreenshot: true,
treeDiff: true
})
expect(vi.mocked(console.error)).not.toHaveBeenCalled()
expect(process.exitCode).toBeUndefined()
})
})
function mockStdin(isTTY: boolean, chunks: string[]): { restore: () => void } {
@@ -1,14 +1,14 @@
import { writeCliScreenshotTempFile } from './cli-screenshot-temp-file'
import { formatBase64PayloadByteCount } from './base64-payload-byte-count'
import { quoteCliCommandArgument } from './shell-command-quote'
import { writeCliScreenshotTempFile } from '../cli-screenshot-temp-file'
import { formatBase64PayloadByteCount } from '../base64-payload-byte-count'
import { quoteCliCommandArgument } from '../shell-command-quote'
import type {
ComputerActionMetadata,
ComputerActionResult,
ComputerListAppsResult,
ComputerListWindowsResult,
ComputerSnapshotResult
} from '../shared/runtime-types'
import type { RuntimeRpcSuccess } from './runtime-client'
} from '../../shared/computer-use-runtime-types'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
export function formatGetAppState(result: ComputerSnapshotResult): string {
const app = result.snapshot.app
@@ -5,36 +5,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime-client', () => {
vi.mock('../runtime/client', () => {
class RuntimeClient {
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
}
class RuntimeClientError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
class RuntimeRpcFailureError extends RuntimeClientError {
readonly response: unknown
constructor(response: unknown) {
super('runtime_error', 'runtime_error')
this.response = response
}
}
return {
RuntimeClient,
RuntimeClientError,
RuntimeRpcFailureError
}
return { RuntimeClient }
})
import { main } from '../index'
@@ -30,10 +30,4 @@ describe('queryComputerTreeText', () => {
].join('\n')
)
})
it('says when nothing matches instead of printing an empty tree', () => {
expect(queryComputerTreeText(TREE, { query: 'underline' })).toContain(
'\n\nNo elements match "underline".\n\nThe focused UI element is'
)
})
})
@@ -2,7 +2,7 @@ import {
joinComputerTreeText,
parseComputerTreeText,
type ComputerTreeElement
} from '../shared/computer-use-tree-text'
} from '../../shared/computer-use-tree-text'
export type ComputerTreeQuery = {
query?: string
@@ -4,22 +4,22 @@ import type {
ComputerListWindowsResult,
ComputerProviderCapabilities,
ComputerSnapshotResult
} from '../../shared/runtime-types'
} from '../../shared/computer-use-runtime-types'
import type { CommandHandler } from '../dispatch'
import {
getOptionalPositiveIntegerFlag,
getOptionalStringFlag,
getRequiredStringFlag
} from '../flags'
import { queryComputerTreeText } from '../computer-tree-query'
import { RuntimeClientError } from '../runtime-client'
import { queryComputerTreeText } from './computer-tree-query'
import { RuntimeClientError } from '../runtime/types'
import {
formatComputerAction,
formatGetAppState,
formatListApps,
formatListWindows,
printResult
} from '../format'
formatListWindows
} from './computer-format'
import { printResult } from '../command-result-output'
import { getComputerCommandTarget } from '../selectors'
import {
getComputerActionObserveFlags,
@@ -1,5 +1,5 @@
import { getOptionalStringFlag, getRequiredStringFlag } from './flags'
import { RuntimeClientError } from './runtime-client'
import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { RuntimeClientError } from '../runtime/types'
export type EmulatorPermissionRequest = {
op: 'grant' | 'revoke' | 'reset'
+90
View File
@@ -0,0 +1,90 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { callMock, remoteMock } = vi.hoisted(() => ({
callMock: vi.fn(),
remoteMock: vi.fn(() => false)
}))
vi.mock('../runtime/client', async () => {
class RuntimeClient {
readonly isRemote: boolean
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
constructor() {
this.isRemote = remoteMock()
}
}
return { RuntimeClient }
})
import { main } from '../index'
describe('orca emulator CLI handlers', () => {
const originalWorkspaceId = process.env.ORCA_WORKSPACE_ID
const originalWorktreeId = process.env.ORCA_WORKTREE_ID
beforeEach(() => {
vi.restoreAllMocks()
callMock.mockReset()
remoteMock.mockReturnValue(false)
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
process.exitCode = undefined
})
afterEach(() => {
if (originalWorkspaceId === undefined) {
delete process.env.ORCA_WORKSPACE_ID
} else {
process.env.ORCA_WORKSPACE_ID = originalWorkspaceId
}
if (originalWorktreeId === undefined) {
delete process.env.ORCA_WORKTREE_ID
} else {
process.env.ORCA_WORKTREE_ID = originalWorktreeId
}
})
it('rejects relative APK paths for remote runtimes', async () => {
remoteMock.mockReturnValue(true)
await main(
['emulator', 'install', 'build/app.apk', '--pairing-code', 'remote', '--worktree', 'all'],
'/repo/project'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Remote emulator install requires --path to be an absolute path on the remote server.'
)
expect(process.exitCode).toBe(1)
})
it('rejects permission reset with package-like arguments', async () => {
await main(
['emulator', 'permissions', 'reset', 'com.example.app', '--worktree', 'all'],
'/repo/project'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'reset does not accept package or permission'
)
expect(process.exitCode).toBe(1)
})
it('rejects grant without a permission before calling the runtime', async () => {
await main(
['emulator', 'permissions', 'grant', 'com.example.app', '--worktree', 'all'],
'/repo/project'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'<permission> is required for grant'
)
expect(process.exitCode).toBe(1)
})
})
@@ -1,7 +1,7 @@
import type { CommandHandler } from '../dispatch'
import { formatLogcat } from '../emulator-logcat-format'
import { parseEmulatorPermissionRequest } from '../emulator-permissions-args'
import { printResult } from '../format'
import { formatLogcat } from './emulator-logcat-format'
import { parseEmulatorPermissionRequest } from './emulator-permissions-args'
import { printResult } from '../command-result-output'
import { resolveRepoPathArgument } from '../repo-path-arguments'
import {
getOptionalPositiveIntegerFlag,
@@ -10,7 +10,7 @@ import {
getRequiredStringFlag
} from '../flags'
import { getEmulatorCommandTarget } from '../selectors'
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import { EMULATOR_ATTACH_RPC_TIMEOUT_MS } from '../../shared/emulator-attach-timeouts'
type EmulatorAttachResult = {
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime-client', () => {
vi.mock('../runtime/client', () => {
class RuntimeClient {
readonly isRemote = false
call = callMock
@@ -10,25 +10,7 @@ vi.mock('../runtime-client', () => {
openOrca = vi.fn()
}
class RuntimeClientError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
class RuntimeRpcFailureError extends RuntimeClientError {
readonly response: unknown
constructor(response: unknown) {
super('runtime_error', 'runtime_error')
this.response = response
}
}
return { RuntimeClient, RuntimeClientError, RuntimeRpcFailureError }
return { RuntimeClient }
})
import { main } from '../index'
@@ -1,6 +1,7 @@
import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open'
import type { HandlerContext } from '../dispatch'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
const NO_APP_WINDOW_MESSAGE =
'This Orca server has no app window, so it cannot open files as tabs. Nothing was opened.'
@@ -1,6 +1,6 @@
import type { RuntimeFileOpenPosition } from '../../shared/file-access/runtime-editor-file-open'
import { getOptionalPositiveIntegerFlag } from '../flags'
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
export function getFileOpenPosition(
flags: Map<string, string | boolean>
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime-client', () => {
vi.mock('../runtime/client', () => {
class RuntimeClient {
readonly isRemote: boolean
call = callMock
@@ -19,29 +19,7 @@ vi.mock('../runtime-client', () => {
}
}
class RuntimeClientError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
class RuntimeRpcFailureError extends RuntimeClientError {
readonly response: unknown
constructor(response: unknown) {
super('runtime_error', 'runtime_error')
this.response = response
}
}
return {
RuntimeClient,
RuntimeClientError,
RuntimeRpcFailureError
}
return { RuntimeClient }
})
import { main } from '../index'
@@ -1,14 +1,14 @@
import { getFileOpenPosition } from './file-open-position'
import type { GitStatusEntry, GitStatusResult } from '../../shared/git/status/git-status-types'
import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-types'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts'
import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation'
import { isRuntimePathAbsolute, relativePathInsideRoot } from '../../shared/cross-platform-path'
import { isWslUncPath, parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { callFileOpen } from './file-open-call'
import { getOptionalWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors'
-146
View File
@@ -1,146 +0,0 @@
import type { CliStatusCaller } from '../shared/orchestration/orchestration-caller-status'
import type { CliStatusResult } from '../shared/runtime-types'
import { formatBrowserActionEffects } from './browser/browser-format'
import { prepareComputerCliJsonResult } from './computer-format'
import type { RuntimeRpcSuccess } from './runtime-client'
export { formatCliError, reportCliError, type CliErrorContext } from './cli-error'
export {
formatComputerAction,
formatGetAppState,
formatListApps,
formatListWindows
} from './computer-format'
export type { ComputerActionFollowUpTarget } from './computer-format'
export {
formatProjectHostSetupCreateResult,
formatProjectHostSetupDeleteResult,
formatProjectHostSetupList,
formatProjectHostSetupResult,
formatProjectHostSetupUpdateResult,
formatProjectList
} from './project-format'
export {
formatTerminalClose,
formatTerminalCreate,
formatTerminalFocus,
formatTerminalList,
formatTerminalRead,
formatTerminalRename,
formatTerminalSetPaneTitle,
formatTerminalSend,
formatTerminalShow,
formatTerminalSplit,
formatTerminalWait,
terminalSendWarnings
} from './terminal-format'
export {
formatAutomationList,
formatAutomationRemoved,
formatAutomationRun,
formatAutomationRuns,
formatAutomationRunsPage,
formatAutomationShow
} from './automation-format'
export type { AutomationListPayload, AutomationShowPayload } from './automation-format'
export {
formatEnvironment,
formatEnvironmentList,
formatMemorySnapshot,
formatRepoList,
formatRepoRefs,
formatRepoShow,
formatWorktreeList,
formatWorktreePs,
formatWorktreeShow
} from './workspace-format'
export function printResult<TResult>(
response: RuntimeRpcSuccess<TResult>,
json: boolean,
formatter: (value: TResult) => string
): void {
if (json) {
console.log(JSON.stringify(prepareComputerCliJsonResult(response), null, 2))
return
}
console.log(formatter(response.result) + formatBrowserActionEffects(response.result))
}
export type HostListEntry = {
kind: 'local' | 'ssh' | 'environment'
name: string
id: string
selector: string
platform?: string
machineName?: string
connected?: boolean
connectionStatus?: string
}
// Explicit host selectors prevent callers from using a display name on the wrong host scope.
export function formatHostList(result: { hosts: HostListEntry[] }): string {
const kindLabel: Record<HostListEntry['kind'], string> = {
local: 'local',
ssh: 'ssh target',
environment: 'orca server'
}
return result.hosts
.map(
(host) =>
`${kindLabel[host.kind].padEnd(11)} ${host.name}${host.machineName ? ` (${host.machineName})` : ''} ${host.platform ?? 'platform unknown'} ${formatHostConnection(host)} -> ${host.selector}`
)
.join('\n')
}
/** What one runtime calls itself; `machineName` is absent when the runtime predates the field. */
export type HostNameResult = {
machineName?: string
platform?: string
}
export function formatHostName(result: HostNameResult): string {
return `${result.machineName ?? 'unknown'}${result.platform ? ` (${result.platform})` : ''}`
}
function formatHostConnection(host: HostListEntry): string {
if (host.kind !== 'ssh') {
return ''
}
if (host.connected === undefined) {
return `connection unknown${host.connectionStatus ? ` (${host.connectionStatus})` : ''}`
}
return host.connected
? `connected${host.connectionStatus ? ` (${host.connectionStatus})` : ''}`
: `not connected${host.connectionStatus ? ` (${host.connectionStatus})` : ''}`
}
export function formatCliStatus(status: CliStatusResult): string {
return [
...(status.target && status.target.kind === 'environment'
? [`target: environment ${status.target.environment}`]
: []),
`appRunning: ${status.app.running}`,
`pid: ${status.app.pid ?? 'none'}`,
`desktopWindowStatus: ${status.app.desktopWindowStatus ?? 'unknown'}`,
`runtimeState: ${status.runtime.state}`,
`runtimeReachable: ${status.runtime.reachable}`,
`runtimeConnectionState: ${status.runtime.connectionState ?? 'unknown'}`,
`runtimeId: ${status.runtime.runtimeId ?? 'none'}`,
`graphState: ${status.graph.state}`,
...(status.runtime.degradations ?? []).map((degradation) => `degraded: ${degradation.message}`),
...(status.caller === undefined ? [] : [`orcaSessionId: ${formatStatusCaller(status.caller)}`])
].join('\n')
}
function formatStatusCaller(caller: CliStatusCaller): string {
if ('refusal' in caller) {
return `none (refused: ${caller.refusal.code})`
}
return `${caller.orcaSessionId}${caller.live ? '' : ' (not live)'}`
}
export function formatStatus(status: CliStatusResult): string {
return formatCliStatus(status)
}
+13 -13
View File
@@ -1,7 +1,7 @@
import type { CommandHandler } from './dispatch'
import { BROWSER_HANDLER_GROUPS } from './browser/browser-handler-groups'
import { JIRA_HANDLER_GROUP } from './jira-handler-group'
import { LINEAR_HANDLER_GROUP } from './linear-handler-group'
import { JIRA_HANDLER_GROUP } from './jira/jira-handler-group'
import { LINEAR_HANDLER_GROUP } from './linear/linear-handler-group'
import { REFERENCE_HANDLER_GROUP } from './reference-handler-group'
import { SERVE_PAIRING_HANDLER_GROUPS } from './serve-pairing-handler-groups'
import { PLUGIN_HANDLER_GROUPS } from './plugin-handler-groups'
@@ -39,7 +39,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
{
name: 'account',
keys: ['account add', 'account list', 'account select', 'account rm'],
load: async () => (await import('./handlers/account.js')).ACCOUNT_HANDLERS
load: async () => (await import('./accounts/account.js')).ACCOUNT_HANDLERS
},
{
name: 'artifacts',
@@ -50,7 +50,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
'artifacts unshare',
'artifacts delete'
],
load: async () => (await import('./handlers/artifacts.js')).ARTIFACT_HANDLERS
load: async () => (await import('./artifacts/artifacts.js')).ARTIFACT_HANDLERS
},
{
name: 'automations',
@@ -63,7 +63,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
'automations run',
'automations runs'
],
load: async () => (await import('./handlers/automations.js')).AUTOMATION_HANDLERS
load: async () => (await import('./automations/automations.js')).AUTOMATION_HANDLERS
},
{
name: 'project',
@@ -94,7 +94,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
{
name: 'file',
keys: ['file open', 'file diff', 'file open-changed'],
load: async () => (await import('./handlers/file.js')).FILE_HANDLERS
load: async () => (await import('./files/file.js')).FILE_HANDLERS
},
{
name: 'terminal',
@@ -174,7 +174,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
'emulator ax',
'emulator logcat'
],
load: async () => (await import('./handlers/emulator.js')).EMULATOR_HANDLERS
load: async () => (await import('./emulator/emulator.js')).EMULATOR_HANDLERS
},
{
name: 'computer',
@@ -194,22 +194,22 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
'computer paste-text',
'computer set-value'
],
load: async () => (await import('./handlers/computer.js')).COMPUTER_HANDLERS
load: async () => (await import('./computer/computer.js')).COMPUTER_HANDLERS
},
{
name: 'agent-hooks',
keys: ['agent hooks prepare-codex', 'agent hooks status', 'agent hooks off', 'agent hooks on'],
load: async () => (await import('./handlers/agent-hooks.js')).AGENT_HOOK_HANDLERS
load: async () => (await import('./agents/agent-hooks.js')).AGENT_HOOK_HANDLERS
},
{
name: 'agent-launch',
keys: ['agent launch'],
load: async () => (await import('./handlers/agent-launch.js')).AGENT_LAUNCH_HANDLERS
load: async () => (await import('./agents/agent-launch.js')).AGENT_LAUNCH_HANDLERS
},
{
name: 'chat',
keys: ['chat rename'],
load: async () => (await import('./handlers/chat.js')).CHAT_HANDLERS
load: async () => (await import('./agents/chat.js')).CHAT_HANDLERS
},
{
name: 'connector',
@@ -259,11 +259,11 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
{
name: 'search',
keys: ['search'],
load: async () => (await import('./handlers/search.js')).SEARCH_HANDLERS
load: async () => (await import('./session-search/search.js')).SEARCH_HANDLERS
},
{
name: 'ports',
keys: ['ports'],
load: async () => (await import('./handlers/ports.js')).PORTS_HANDLERS
load: async () => (await import('./workspace-ports/ports.js')).PORTS_HANDLERS
}
]
@@ -1,76 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AUTOMATION_HANDLERS } from './automations'
const owner = { selector: { kind: 'ssh', targetId: 'box', targetGeneration: 4 } }
function ok(result: unknown): unknown {
return { id: 'request-1', ok: true, result, _meta: { runtimeId: 'runtime-1' } }
}
function clientAnsweringShow(owner: unknown): { call: ReturnType<typeof vi.fn> } {
const call = vi.fn(async (method: string) =>
method === 'automation.show'
? ok(owner === undefined ? { automation: { id: 'a1' } } : { automation: { id: 'a1' }, owner })
: ok({ automation: { id: 'a1' }, removed: true, id: 'a1', run: { id: 'r1' }, runs: [] })
)
return { call }
}
afterEach(() => vi.restoreAllMocks())
// Generation-bearing SSH records reject mutations that omit the owner precondition.
describe('CLI automation mutations carry the owner they read', () => {
it.each([
['automations remove', 'automation.delete'],
['automations run', 'automation.runNow']
])('%s sends the owner from automation.show to %s', async (command, method) => {
const { call } = clientAnsweringShow(owner)
vi.spyOn(console, 'log').mockImplementation(() => undefined)
await AUTOMATION_HANDLERS[command]!({
client: { call } as never,
cwd: '/tmp',
flags: new Map([['id', 'a1']]),
json: true
})
expect(call).toHaveBeenNthCalledWith(1, 'automation.show', { id: 'a1' })
expect(call).toHaveBeenNthCalledWith(2, method, { id: 'a1', expectedOwner: owner })
})
it('edit sends the owner alongside the update payload', async () => {
const { call } = clientAnsweringShow(owner)
vi.spyOn(console, 'log').mockImplementation(() => undefined)
await AUTOMATION_HANDLERS['automations edit']!({
client: { call } as never,
cwd: '/tmp',
flags: new Map([
['id', 'a1'],
['name', 'renamed']
]),
json: true
})
expect(call).toHaveBeenNthCalledWith(
2,
'automation.update',
expect.objectContaining({ id: 'a1', expectedOwner: owner })
)
})
// Older hosts supply no owner and require no precondition.
it('omits the precondition when the host reports no owner', async () => {
const { call } = clientAnsweringShow(undefined)
vi.spyOn(console, 'log').mockImplementation(() => undefined)
await AUTOMATION_HANDLERS['automations run']!({
client: { call } as never,
cwd: '/tmp',
flags: new Map([['id', 'a1']]),
json: true
})
expect(call).toHaveBeenNthCalledWith(2, 'automation.runNow', { id: 'a1' })
})
})
+1 -1
View File
@@ -7,7 +7,7 @@ import {
getOptionalStringFlag,
getRequiredStringFlag
} from '../flags'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime-client'
import { getRequiredWorktreeSelector } from '../selectors'
+2 -1
View File
@@ -1,7 +1,8 @@
import { spawn } from 'node:child_process'
import { resolve } from 'node:path'
import type { CommandHandler } from '../dispatch'
import { formatCliStatus, formatStatus, printResult } from '../format'
import { formatCliStatus, formatCliStatus as formatStatus } from '../runtime/cli-status-format'
import { printResult } from '../command-result-output'
import { RuntimeClientError, serveOrcaApp } from '../runtime-client'
import { getOptionalServeBind } from '../runtime/serve-bind-flag'
import { stripElectronRunAsNode } from '../runtime/orca-app-executable'
+2 -1
View File
@@ -1,6 +1,7 @@
import type { MemorySnapshot } from '../../shared/process-stats-types'
import type { CommandHandler } from '../dispatch'
import { formatMemorySnapshot, printResult } from '../format'
import { formatMemorySnapshot } from '../workspace-format'
import { printResult } from '../command-result-output'
import { TERMINAL_DAEMON_HANDLERS } from './terminal-daemon'
export const DIAGNOSTICS_HANDLERS: Record<string, CommandHandler> = {
-185
View File
@@ -1,185 +0,0 @@
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { callMock, remoteMock } = vi.hoisted(() => ({
callMock: vi.fn(),
remoteMock: vi.fn(() => false)
}))
vi.mock('../runtime-client', async () => {
class RuntimeClient {
readonly isRemote: boolean
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
constructor() {
this.isRemote = remoteMock()
}
}
// Error formatting uses instanceof, so preserve the production error classes.
const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js')
return { RuntimeClient, RuntimeClientError, RuntimeRpcFailureError }
})
import { main } from '../index'
import { okFixture, queueFixtures } from '../test-fixtures'
describe('orca emulator CLI handlers', () => {
const originalWorkspaceId = process.env.ORCA_WORKSPACE_ID
const originalWorktreeId = process.env.ORCA_WORKTREE_ID
beforeEach(() => {
vi.restoreAllMocks()
callMock.mockReset()
remoteMock.mockReturnValue(false)
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
process.exitCode = undefined
})
afterEach(() => {
if (originalWorkspaceId === undefined) {
delete process.env.ORCA_WORKSPACE_ID
} else {
process.env.ORCA_WORKSPACE_ID = originalWorkspaceId
}
if (originalWorktreeId === undefined) {
delete process.env.ORCA_WORKTREE_ID
} else {
process.env.ORCA_WORKTREE_ID = originalWorktreeId
}
})
it('resolves relative APK paths before calling the runtime', async () => {
queueFixtures(callMock, okFixture('req_install', { ok: true }))
await main(
['emulator', 'install', 'build/app.apk', '--reinstall', '--worktree', 'all'],
'/repo/project'
)
expect(callMock).toHaveBeenCalledWith('emulator.install', {
path: path.resolve('/repo/project', 'build/app.apk'),
reinstall: true,
device: undefined,
emulator: undefined,
worktree: undefined
})
})
it('uses the folder workspace exported by the current Orca terminal', async () => {
process.env.ORCA_WORKSPACE_ID = 'folder:folder-1'
delete process.env.ORCA_WORKTREE_ID
callMock.mockResolvedValue(
okFixture('req_attach', {
attached: true,
info: { deviceUdid: 'device-1', streamUrl: 'scrcpy://device-1' }
})
)
await main(['emulator', 'attach', 'device-1'], '/folder/project')
expect(callMock).toHaveBeenCalledOnce()
expect(callMock).toHaveBeenCalledWith(
'emulator.attach',
{ device: 'device-1', worktree: 'folder:folder-1', focus: false },
{ timeoutMs: 240_000 }
)
})
it('uses the current git worktree exported by the Orca terminal', async () => {
process.env.ORCA_WORKSPACE_ID = 'folder:stale-parent'
process.env.ORCA_WORKTREE_ID = 'repo-1::/repo/project '
callMock.mockResolvedValue(
okFixture('req_attach', {
attached: true,
info: { deviceUdid: 'device-1', streamUrl: 'scrcpy://device-1' }
})
)
await main(['emulator', 'attach', 'device-1'], '/repo/project')
expect(callMock).toHaveBeenCalledOnce()
expect(callMock).toHaveBeenCalledWith(
'emulator.attach',
{ device: 'device-1', worktree: 'repo-1::/repo/project ', focus: false },
{ timeoutMs: 240_000 }
)
})
it('rejects relative APK paths for remote runtimes', async () => {
remoteMock.mockReturnValue(true)
await main(
['emulator', 'install', 'build/app.apk', '--pairing-code', 'remote', '--worktree', 'all'],
'/repo/project'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Remote emulator install requires --path to be an absolute path on the remote server.'
)
expect(process.exitCode).toBe(1)
})
it('preserves absolute server APK paths for remote runtimes', async () => {
remoteMock.mockReturnValue(true)
queueFixtures(callMock, okFixture('req_install', { ok: true }))
await main(
['emulator', 'install', 'C:\\tmp\\app.apk', '--pairing-code', 'remote', '--worktree', 'all'],
'/repo/project'
)
expect(callMock).toHaveBeenCalledWith('emulator.install', {
path: 'C:\\tmp\\app.apk',
reinstall: false,
device: undefined,
emulator: undefined,
worktree: undefined
})
})
it('allows device-wide permission reset without package or permission', async () => {
queueFixtures(callMock, okFixture('req_permissions', { ok: true }))
await main(['emulator', 'permissions', 'reset', '--worktree', 'all'], '/repo/project')
expect(callMock).toHaveBeenCalledWith('emulator.permissions', {
op: 'reset',
package: undefined,
permission: undefined,
device: undefined,
emulator: undefined,
worktree: undefined
})
})
it('rejects permission reset with package-like arguments', async () => {
await main(
['emulator', 'permissions', 'reset', 'com.example.app', '--worktree', 'all'],
'/repo/project'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'reset does not accept package or permission'
)
expect(process.exitCode).toBe(1)
})
it('rejects grant without a permission before calling the runtime', async () => {
await main(
['emulator', 'permissions', 'grant', 'com.example.app', '--worktree', 'all'],
'/repo/project'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'<permission> is required for grant'
)
expect(process.exitCode).toBe(1)
})
})
+3 -8
View File
@@ -1,12 +1,7 @@
import type { CommandHandler } from '../dispatch'
import {
formatEnvironment,
formatEnvironmentList,
formatHostList,
formatHostName,
printResult,
type HostNameResult
} from '../format'
import { formatEnvironment, formatEnvironmentList } from '../workspace-format'
import { formatHostList, formatHostName, type HostNameResult } from '../hosts/host-format'
import { printResult } from '../command-result-output'
import { parseHostFlag } from '../execution-host-flag'
import {
fetchSshTargetSummaries,
@@ -7,7 +7,8 @@ import type {
import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types'
import { FOLDER_WORKSPACE_UNIQUE_ID_MUTATION_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
import { folderIdOfSelector, folderWorkspaceKey } from '../../shared/workspace-scope'
import { formatWorktreeShow, printResult } from '../format'
import { formatWorktreeShow } from '../workspace-format'
import { printResult } from '../command-result-output'
import { getOptionalStringFlag, getOptionalStringFlagAllowingEmpty } from '../flags'
import { RuntimeClientError, type RuntimeClient, type RuntimeRpcSuccess } from '../runtime-client'
import { getWorktreeReadFlags } from './worktree-unread-flag'
@@ -1,136 +0,0 @@
import { EventEmitter } from 'node:events'
import type { ChildProcess } from 'node:child_process'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
terminateInteractiveLoginProcess,
terminateWindowsLoginProcessTree
} from './interactive-login-interruption'
function loginChild(pid = 4321): ChildProcess & EventEmitter {
return Object.assign(new EventEmitter(), {
kill: vi.fn(),
pid
}) as unknown as ChildProcess & EventEmitter
}
afterEach(() => {
vi.useRealTimers()
})
describe('terminateInteractiveLoginProcess', () => {
it('runs bounded taskkill /T /F without a shell', async () => {
const execFileImpl = vi.fn(
(
_command: string,
_args: readonly string[],
_options: { timeout?: number; windowsHide?: boolean },
callback: (error: Error | null) => void
) => callback(null)
)
await terminateWindowsLoginProcessTree(4321, execFileImpl as never)
expect(execFileImpl).toHaveBeenCalledWith(
'taskkill',
['/pid', '4321', '/T', '/F'],
{ timeout: 5_000, windowsHide: true },
expect.any(Function)
)
})
it('waits for both Windows tree termination and physical wrapper close', async () => {
const child = loginChild()
let finishTreeKill: (() => void) | undefined
const killWindowsTree = vi.fn(
() =>
new Promise<void>((resolve) => {
finishTreeKill = resolve
})
)
let terminated = false
const pending = terminateInteractiveLoginProcess(child, 'SIGTERM', {
platform: 'win32',
killWindowsTree
}).then(() => {
terminated = true
})
expect(killWindowsTree).toHaveBeenCalledWith(4321)
child.emit('close', 1)
await Promise.resolve()
expect(terminated).toBe(false)
finishTreeKill?.()
await pending
expect(child.kill).not.toHaveBeenCalled()
})
it('bounds Windows close waits and falls back to the direct wrapper', async () => {
vi.useFakeTimers()
const child = loginChild()
let terminated = false
const pending = terminateInteractiveLoginProcess(child, 'SIGINT', {
platform: 'win32',
killWindowsTree: vi.fn().mockResolvedValue(undefined)
}).then(() => {
terminated = true
})
await vi.advanceTimersByTimeAsync(999)
expect(child.kill).not.toHaveBeenCalled()
expect(terminated).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(child.kill).toHaveBeenCalledOnce()
expect(child.kill).toHaveBeenCalledWith(undefined)
await vi.advanceTimersByTimeAsync(999)
expect(terminated).toBe(false)
await vi.advanceTimersByTimeAsync(1)
await pending
expect(terminated).toBe(true)
})
it('forwards the interrupt signal to a direct POSIX child and awaits close', async () => {
const child = loginChild()
let terminated = false
const pending = terminateInteractiveLoginProcess(child, 'SIGHUP', {
platform: 'linux'
}).then(() => {
terminated = true
})
expect(child.kill).toHaveBeenCalledWith('SIGHUP')
await Promise.resolve()
expect(terminated).toBe(false)
child.emit('close', 1)
await pending
expect(child.kill).toHaveBeenCalledOnce()
})
it('force-kills an unresponsive POSIX child before the final bounded wait', async () => {
vi.useFakeTimers()
const child = loginChild()
let terminated = false
const pending = terminateInteractiveLoginProcess(child, 'SIGINT', {
platform: 'darwin'
}).then(() => {
terminated = true
})
await vi.advanceTimersByTimeAsync(4_999)
expect(child.kill).toHaveBeenCalledExactlyOnceWith('SIGINT')
expect(terminated).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(child.kill).toHaveBeenNthCalledWith(1, 'SIGINT')
expect(child.kill).toHaveBeenNthCalledWith(2, 'SIGKILL')
await vi.advanceTimersByTimeAsync(999)
expect(terminated).toBe(false)
await vi.advanceTimersByTimeAsync(1)
await pending
expect(terminated).toBe(true)
})
})
-557
View File
@@ -1,557 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime-client', async () => {
class RuntimeClient {
readonly isRemote: boolean
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
constructor(
_userDataPath?: string,
_requestTimeoutMs?: number,
remotePairingCode = process.env.ORCA_PAIRING_CODE ?? null,
environmentSelector = process.env.ORCA_ENVIRONMENT ?? null
) {
this.isRemote = Boolean(remotePairingCode || environmentSelector)
}
}
// Error formatting uses instanceof, so preserve the production error classes.
const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js')
return {
RuntimeClient,
RuntimeClientError,
RuntimeRpcFailureError
}
})
import { main } from '../index'
import { okFixture, queueFixtures } from '../test-fixtures'
describe('orca linear CLI handlers', () => {
const originalEnv = { ...process.env }
beforeEach(() => {
vi.restoreAllMocks()
callMock.mockReset()
process.env = { ...originalEnv }
// Clear real terminal/worktree/pairing hints inherited from the test runner.
delete process.env.ORCA_WORKTREE_ID
delete process.env.ORCA_TERMINAL_HANDLE
delete process.env.ORCA_PAIRING_CODE
delete process.env.ORCA_ENVIRONMENT
process.exitCode = undefined
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
})
it('maps --full issue reads to read-only issueContext RPC', async () => {
queueFixtures(callMock, okFixture('req_linear', issueResult()))
await main(['linear', 'issue', 'ENG-123', '--full', '--json'], '/tmp/repo')
expect(callMock).toHaveBeenCalledWith(
'linear.issueContext',
{
input: 'ENG-123',
current: false,
workspaceId: undefined,
include: {
comments: true,
children: true,
attachments: true,
relations: true,
activity: true
},
depth: 2,
context: {
remote: false,
cwd: '/tmp/repo'
}
},
{ timeoutMs: 120_000 }
)
})
it.each([
{ flags: [], depth: 0, children: false },
{ flags: ['--children'], depth: 2, children: true },
{ flags: ['--children', '--depth', '0'], depth: 0, children: true }
])('routes child depth from CLI flags: $flags', async ({ flags, depth, children }) => {
queueFixtures(callMock, okFixture('req_linear', issueResult()))
await main(['linear', 'issue', 'ENG-123', ...flags, '--json'], '/tmp/repo')
expect(callMock).toHaveBeenCalledWith(
'linear.issueContext',
expect.objectContaining({ depth, include: expect.objectContaining({ children }) }),
{ timeoutMs: undefined }
)
expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0])).result).toEqual(
issueResult()
)
})
it('prints truncation on human stdout and in JSON without using stderr for JSON', async () => {
const listResult = {
issues: [
{
id: 'issue-1',
identifier: 'ENG-1',
title: 'Fix auth',
url: 'https://linear.app/acme/issue/ENG-1',
labels: [],
workspace: { id: 'workspace-1', name: 'Acme' }
}
],
truncated: true,
meta: {
limit: 1,
returned: 1,
hasMore: true,
nextCursor: 'next-page',
orderBy: 'updatedAt',
workspaceId: 'workspace-1',
partial: false,
workspaceErrors: []
}
}
queueFixtures(callMock, okFixture('req_list', listResult))
await main(['linear', 'list-issues', '--limit', '1'], '/tmp/repo')
expect(vi.mocked(console.log).mock.calls[0][0]).toContain('truncated: showing 1')
expect(
vi.mocked(console.error).mock.calls.some((call) => String(call[0]).includes('more results'))
).toBe(true)
vi.mocked(console.log).mockClear()
vi.mocked(console.error).mockClear()
queueFixtures(callMock, okFixture('req_list_json', listResult))
await main(['linear', 'list-issues', '--limit', '1', '--json'], '/tmp/repo')
const jsonOut = String(vi.mocked(console.log).mock.calls[0][0])
expect(jsonOut).toContain('"truncated": true')
expect(vi.mocked(console.error)).not.toHaveBeenCalled()
})
it('passes verified current-context hints without resolving cwd for remote runtimes', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_123'
process.env.ORCA_WORKTREE_ID = 'repo::/srv/app'
process.env.ORCA_PAIRING_CODE = 'orca://pair?payload=bad'
queueFixtures(callMock, okFixture('req_linear', issueResult()))
await main(['linear', 'issue', '--current', '--comments', '--json'], '/client/repo')
expect(callMock).toHaveBeenCalledWith(
'linear.issueContext',
expect.objectContaining({
input: undefined,
current: true,
include: expect.objectContaining({ comments: true }),
context: {
remote: true,
worktreeId: 'repo::/srv/app',
terminalHandle: 'term_123'
}
}),
{ timeoutMs: undefined }
)
})
it('rejects --depth unless children are requested', async () => {
await main(['linear', 'issue', 'ENG-123', '--depth', '3'], '/tmp/repo')
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'--depth requires --children or --full'
)
expect(process.exitCode).toBe(1)
})
it('maps search to agent search RPC with capped limit', async () => {
queueFixtures(
callMock,
okFixture('req_search', {
issues: [],
meta: { query: 'auth', workspaceId: 'all', limit: 50, returned: 0, limitReached: false }
})
)
await main(['linear', 'search', 'auth', '--workspace', 'all', '--limit', '500'], '/tmp/repo')
expect(callMock).toHaveBeenCalledWith('linear.agentSearchIssues', {
query: 'auth',
limit: 50,
workspaceId: 'all'
})
})
it('maps relation writes to the current-issue perspective', async () => {
queueFixtures(callMock, okFixture('req_relation', relationWriteResult()))
await main(
[
'linear',
'relation',
'add',
'ENG-123',
'--related',
'ENG-456',
'--type',
'blocked-by',
'--json'
],
'/tmp/repo'
)
expect(callMock).toHaveBeenCalledWith(
'linear.issueRelationWrite',
{
input: 'ENG-123',
current: false,
workspaceId: undefined,
relatedInput: 'ENG-456',
relationship: 'blockedBy',
operation: 'add',
context: { remote: false, cwd: '/tmp/repo' }
},
{ timeoutMs: 75_000 }
)
})
it('rejects impossible due dates before dispatch', async () => {
await main(['linear', 'due-date', 'set', 'ENG-123', '--to', '2026-02-30'], '/tmp/repo')
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('real calendar date')
})
it('preserves repeated labels for label updates', async () => {
queueFixtures(callMock, okFixture('req_label', taskUpdateResult('labels')))
await main(
['linear', 'label', 'add', 'ENG-123', '--label', 'Bug', '--label', 'Regression', '--json'],
'/tmp/repo'
)
expect(callMock).toHaveBeenCalledWith(
'linear.issueUpdateTask',
expect.objectContaining({
input: 'ENG-123',
operation: 'labels',
labelMode: 'add',
labels: ['Bug', 'Regression']
}),
{ timeoutMs: 75_000 }
)
})
it('requires exact write targets for issue writes', async () => {
await main(['linear', 'comment', 'add', '--body', 'done'], '/tmp/repo')
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Pass a Linear issue id or --current'
)
expect(process.exitCode).toBe(1)
})
it('rejects --workspace all for writes before dispatch', async () => {
await main(
[
'linear',
'attach',
'ENG-123',
'--url',
'https://example.com/review/123',
'--workspace',
'all'
],
'/tmp/repo'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'--workspace all is not valid for Linear writes'
)
expect(process.exitCode).toBe(1)
})
it('reads comment bodies from stdin and passes retry write ids through', async () => {
const stdin = mockStdin(false, ['line one\n', 'line two'])
queueFixtures(callMock, okFixture('req_comment', commentAddResult()))
try {
await main(
[
'linear',
'comment',
'add',
'--current',
'--body-file',
'-',
'--reply-to',
'comment-parent',
'--write-id',
'123e4567-e89b-12d3-a456-426614174000',
'--json'
],
'/tmp/repo'
)
} finally {
stdin.restore()
}
expect(callMock).toHaveBeenCalledWith(
'linear.issueAddComment',
{
input: undefined,
current: true,
workspaceId: undefined,
body: 'line one\nline two',
replyTo: 'comment-parent',
writeId: '123e4567-e89b-12d3-a456-426614174000',
context: {
remote: false,
cwd: '/tmp/repo'
}
},
{ timeoutMs: 75_000 }
)
})
it('edits a comment from stdin and deletes one through the rm alias', async () => {
const commentId = '9f3c2a10-1111-4222-8333-444455556666'
const stdin = mockStdin(false, ['fixed body'])
queueFixtures(
callMock,
okFixture('req_edit', commentAddResult()),
okFixture('req_delete', commentAddResult())
)
try {
await main(['linear', 'comment', 'edit', commentId, '--body-file', '-'], '/tmp/repo')
} finally {
stdin.restore()
}
await main(['linear', 'comment', 'rm', commentId, '--workspace', 'w', '--json'], '/tmp/repo')
expect(callMock).toHaveBeenNthCalledWith(
1,
'linear.commentEdit',
{ commentId, body: 'fixed body', workspaceId: undefined },
{ timeoutMs: 75_000 }
)
expect(callMock).toHaveBeenNthCalledWith(
2,
'linear.commentDelete',
{ commentId, workspaceId: 'w' },
{ timeoutMs: 75_000 }
)
expect(vi.mocked(console.log).mock.calls[0][0]).toBe('Edited comment comment-id on ENG-123.')
})
it('rejects malformed write ids before dispatch', async () => {
await main(
[
'linear',
'attach',
'ENG-123',
'--url',
'https://example.com/review/123',
'--write-id',
'not-a-uuid',
'--json'
],
'/tmp/repo'
)
expect(callMock).not.toHaveBeenCalled()
const payload = JSON.parse(String(vi.mocked(console.log).mock.calls[0][0])) as {
error: { code: string }
}
expect(payload.error.code).toBe('linear_invalid_write_id')
})
it('maps MCP-style save-issue updates and explicit clears', async () => {
queueFixtures(callMock, okFixture('req_save', createResult()))
await main(
[
'linear',
'save-issue',
'ENG-123',
'--title',
'Updated title',
'--assignee',
'null',
'--estimate',
'null',
'--due-date',
'null',
'--project',
'null',
'--label',
'Bug',
'--json'
],
'/tmp/repo'
)
expect(callMock).toHaveBeenCalledWith(
'linear.saveIssue',
expect.objectContaining({
input: 'ENG-123',
title: 'Updated title',
assignee: null,
estimate: null,
dueDate: null,
project: null,
labels: ['Bug']
}),
{ timeoutMs: 75_000 }
)
})
it('rejects duplicate body inputs before dispatch', async () => {
await main(
['linear', 'create', '--title', 'Bug', '--body', 'one', '--body-file', 'body.md'],
'/tmp/repo'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Use either --body or --body-file')
})
})
function issueResult(): unknown {
return {
issue: {
id: 'issue-id',
identifier: 'ENG-123',
title: 'Fix auth',
url: 'https://linear.app/acme/issue/ENG-123',
state: { name: 'Todo' },
team: { name: 'Engineering' },
labels: []
},
meta: {
requested: {
current: false,
include: {
comments: false,
children: false,
attachments: false,
relations: false,
activity: false
},
depth: 2
},
resolved: {
id: 'issue-id',
identifier: 'ENG-123',
workspaceId: 'workspace-1',
workspaceName: 'Acme'
},
partial: false,
includeErrors: [],
sections: {}
}
}
}
function commentAddResult(): unknown {
return {
comment: { id: 'comment-id', url: null, parentId: 'comment-parent' },
issue: { id: 'issue-id', identifier: 'ENG-123', url: 'https://linear.app/acme/issue/ENG-123' },
meta: {
workspaceId: 'workspace-1',
bodyChars: 17,
writeId: '123e4567-e89b-12d3-a456-426614174000',
deduplicated: false
}
}
}
function createResult(): unknown {
return {
issue: {
id: 'issue-child',
identifier: 'ENG-456',
title: 'Follow-up bug',
url: 'https://linear.app/acme/issue/ENG-456',
team: { id: 'team-eng', key: 'ENG', name: 'Engineering' },
state: { id: 'state-triage', name: 'Triage' },
parent: { id: 'issue-id', identifier: 'ENG-123' }
},
meta: {
workspaceId: 'workspace-1',
writeId: '123e4567-e89b-12d3-a456-426614174000',
deduplicated: false
}
}
}
function taskUpdateResult(operation: string): unknown {
return {
issue: { id: 'issue-id', identifier: 'ENG-123', url: 'https://linear.app/acme/issue/ENG-123' },
operation,
previous: {},
current: {},
meta: { workspaceId: 'workspace-1', alreadySet: false }
}
}
function relationWriteResult(): unknown {
return {
issue: {
id: 'issue-id',
identifier: 'ENG-123',
title: 'Current',
url: 'https://linear.app/acme/issue/ENG-123'
},
relatedIssue: {
id: 'related-id',
identifier: 'ENG-456',
title: 'Related',
url: 'https://linear.app/acme/issue/ENG-456'
},
relation: {
id: 'relation-id',
type: 'blocks',
direction: 'inbound',
relationship: 'blockedBy'
},
operation: 'add',
meta: { workspaceId: 'workspace-1', alreadySet: false }
}
}
function mockStdin(isTTY: boolean, chunks: string[]): { restore: () => void } {
const stdin = process.stdin
const previousIsTTY = stdin.isTTY
const previousAsyncIterator = stdin[Symbol.asyncIterator]
Object.defineProperty(stdin, 'isTTY', {
configurable: true,
value: isTTY
})
;(stdin as unknown as Record<symbol, unknown>)[Symbol.asyncIterator] = async function* () {
for (const chunk of chunks) {
yield chunk
}
return undefined
}
return {
restore: () => {
Object.defineProperty(stdin, 'isTTY', {
configurable: true,
value: previousIsTTY
})
if (previousAsyncIterator) {
;(stdin as unknown as Record<symbol, unknown>)[Symbol.asyncIterator] = previousAsyncIterator
} else {
Reflect.deleteProperty(stdin, Symbol.asyncIterator)
}
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
// Updates can close this connection mid-call; report the outcome from status after the runtime returns.
import type { OrcadManagedRuntimeStatus } from '../../shared/orcad-managed-runtime'
import type { HandlerContext } from '../dispatch'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
const STATUS_ATTEMPTS = 15
+1 -1
View File
@@ -12,7 +12,7 @@ import { MANAGED_SERVER_RUNTIME_CAPABILITY } from '../../shared/protocol-version
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { getRequiredStringFlag } from '../flags'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
import { formatManagedServerStatus } from './managed-server-format'
import { reportAfterClosedConnection } from './managed-server-reconnect'
@@ -4,24 +4,17 @@ 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('../command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
import { RuntimeClientError } from '../runtime-client'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
function staleHandleError(): RuntimeClientError {
return new RuntimeClientError('terminal_handle_stale', 'terminal_handle_stale')
}
function stubStaleHandleRemint(liveHandle: string, downstream: unknown): void {
callMock
.mockResolvedValueOnce(notLiveIdentity())
.mockResolvedValueOnce({ result: { terminal: { handle: liveHandle } } })
.mockResolvedValueOnce(downstream)
}
function stubStaleHandleRemintFailure(error: RuntimeClientError): void {
callMock.mockResolvedValueOnce(notLiveIdentity()).mockRejectedValueOnce(error)
}
@@ -30,10 +23,6 @@ function notLiveIdentity(): { result: { identity: { live: false } } } {
return { result: { identity: { live: false } } }
}
function liveIdentity(handle: string): { result: { identity: { handle: string; live: true } } } {
return { result: { identity: { handle, live: true } } }
}
afterEach(() => {
getTerminalHandleMock.mockReset()
if (originalTerminalHandle === undefined) {
@@ -66,15 +55,6 @@ describe('orchestration dispatch coordinator handle', () => {
json
} as never)
const invokeDispatchShow = (flags: Map<string, string | boolean>, json = true) =>
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This handler uses only client.call, supplied by the fixture; no RuntimeClient lifecycle methods are accessed.
ORCHESTRATION_HANDLERS['orchestration dispatch-show']({
flags,
client: { call: callMock },
cwd: '/tmp/repo',
json
} as never)
const invokeRun = (flags: Map<string, string | boolean>) =>
ORCHESTRATION_HANDLERS['orchestration coordinator-start']({
flags,
@@ -83,92 +63,6 @@ describe('orchestration dispatch coordinator handle', () => {
json: true
} as never)
it('allows a dry run without a recipient and returns only its preamble', async () => {
callMock.mockResolvedValue({
result: { dispatch: null, dryRun: true, preamble: 'preview preamble' }
})
await invokeDispatch(
new Map<string, string | boolean>([
['task', 'task_1'],
['from', 'terminal_coordinator'],
['dry-run', true],
['return-preamble', true],
['full', true]
]),
false
)
expect(callMock).toHaveBeenCalledWith('orchestration.dispatch', {
task: 'task_1',
run: undefined,
to: undefined,
from: 'terminal_coordinator',
inject: undefined,
dryRun: true,
returnPreamble: true,
devMode: false
})
expect(renderedValue({ dispatch: null, dryRun: true, preamble: 'preview preamble' })).toBe(
'preview preamble'
)
})
it('does not resolve coordinator identity for a non-preamble dispatch lookup', async () => {
callMock.mockResolvedValue({ result: { dispatch: null } })
await invokeDispatchShow(
new Map<string, string | boolean>([
['task', 'task_1'],
['full', true]
]),
false
)
expect(callMock).toHaveBeenCalledWith('orchestration.dispatchShow', {
task: 'task_1',
preamble: undefined,
from: undefined,
devMode: false
})
expect(getTerminalHandleMock).not.toHaveBeenCalled()
expect(renderedValue({ dispatch: null })).toBe('No dispatch context found.')
})
it('remints a stale coordinator env handle from the caller pane key', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord'
process.env.ORCA_PANE_KEY = 'tab_coord:leaf_coord'
stubStaleHandleRemint('term_live_coord', {
result: { dispatch: { id: 'ctx_1', task_id: 'task_1', status: 'dispatched' } }
})
getTerminalHandleMock.mockRejectedValue(new Error('active terminal fallback is unsafe'))
await invokeDispatch(
new Map<string, string | boolean>([
['task', 'task_1'],
['to', 'term_worker'],
['inject', true]
])
)
expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', {
terminal: 'term_stale_coord'
})
expect(callMock).toHaveBeenNthCalledWith(2, 'terminal.resolvePane', {
paneKey: 'tab_coord:leaf_coord'
})
expect(getTerminalHandleMock).not.toHaveBeenCalled()
expect(callMock).toHaveBeenNthCalledWith(3, 'orchestration.dispatch', {
task: 'task_1',
to: 'term_worker',
from: 'term_live_coord',
inject: true,
dryRun: undefined,
returnPreamble: undefined,
devMode: false
})
})
it('rejects stale coordinator env handles when the caller pane cannot be proven', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord'
callMock.mockRejectedValueOnce(staleHandleError())
@@ -218,35 +112,6 @@ describe('orchestration dispatch coordinator handle', () => {
expect(getTerminalHandleMock).not.toHaveBeenCalled()
})
it('uses a live coordinator handle for dispatch-show preamble previews', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord'
process.env.ORCA_PANE_KEY = 'tab_coord:leaf_coord'
stubStaleHandleRemint('term_live_coord', {
result: { dispatch: null, preamble: 'preamble' }
})
getTerminalHandleMock.mockRejectedValue(new Error('active terminal fallback is unsafe'))
await invokeDispatchShow(
new Map<string, string | boolean>([
['task', 'task_1'],
['preamble', true]
])
)
expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', {
terminal: 'term_stale_coord'
})
expect(callMock).toHaveBeenNthCalledWith(2, 'terminal.resolvePane', {
paneKey: 'tab_coord:leaf_coord'
})
expect(callMock).toHaveBeenNthCalledWith(3, 'orchestration.dispatchShow', {
task: 'task_1',
preamble: true,
from: 'term_live_coord',
devMode: false
})
})
it('retires the legacy coordinator command without runtime effects', async () => {
await expect(
invokeRun(new Map<string, string | boolean>([['spec', 'run the plan']]))
@@ -278,28 +143,6 @@ describe('orchestration task-create caller handle', () => {
json: true
} as never)
it('records a live env terminal handle as task creator', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_creator'
callMock
.mockResolvedValueOnce(liveIdentity('term_creator'))
.mockResolvedValueOnce({ result: { task: { id: 'task_1', status: 'ready' } } })
await invokeTaskCreate(new Map<string, string | boolean>([['spec', 'do work']]))
expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', {
terminal: 'term_creator'
})
expect(callMock).toHaveBeenNthCalledWith(2, 'orchestration.taskCreate', {
spec: 'do work',
taskTitle: undefined,
displayName: undefined,
deps: undefined,
parent: undefined,
run: undefined,
callerTerminalHandle: 'term_creator'
})
})
it('fails closed when a stale task creator handle cannot be reminted', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_stale'
callMock.mockRejectedValueOnce(staleHandleError())
@@ -315,40 +158,4 @@ describe('orchestration task-create caller handle', () => {
expect(getTerminalHandleMock).not.toHaveBeenCalled()
expect(callMock).toHaveBeenCalledTimes(1)
})
it('remints a stale task creator env handle from the caller pane key', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_stale'
process.env.ORCA_PANE_KEY = 'tab_creator:leaf_creator'
stubStaleHandleRemint('term_live', {
result: { task: { id: 'task_1', status: 'ready' } }
})
getTerminalHandleMock.mockRejectedValue(new Error('active terminal fallback is unsafe'))
await invokeTaskCreate(new Map<string, string | boolean>([['spec', 'do work']]))
expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', {
terminal: 'term_stale'
})
expect(callMock).toHaveBeenNthCalledWith(2, 'terminal.resolvePane', {
paneKey: 'tab_creator:leaf_creator'
})
expect(getTerminalHandleMock).not.toHaveBeenCalled()
expect(callMock).toHaveBeenNthCalledWith(3, 'orchestration.taskCreate', {
spec: 'do work',
taskTitle: undefined,
displayName: undefined,
deps: undefined,
parent: undefined,
run: undefined,
callerTerminalHandle: 'term_live'
})
})
})
function renderedValue(value: unknown): string {
const formatter = vi.mocked(printResult).mock.calls[0]?.[2]
if (!formatter) {
throw new Error('Expected a plain output formatter')
}
return formatter(value)
}
@@ -6,7 +6,7 @@ const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE
const originalPaneKey = process.env.ORCA_PANE_KEY
const printResultMock = vi.hoisted(() => vi.fn())
vi.mock('../format', () => ({ printResult: printResultMock }))
vi.mock('../command-result-output', () => ({ printResult: printResultMock }))
vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
@@ -41,24 +41,6 @@ describe('orchestration check identity', () => {
json
} as never)
it('carries the caller pane key when the environment handle may be stale', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord'
process.env.ORCA_PANE_KEY = 'tab_coord:leaf_coord'
getTerminalHandleMock.mockRejectedValue(new Error('active terminal fallback is unsafe'))
await invokeCheck(new Map<string, string | boolean>([['wait', true]]))
expect(getTerminalHandleMock).not.toHaveBeenCalled()
expect(callMock).toHaveBeenCalledWith(
'orchestration.check',
expect.objectContaining({
terminal: 'term_stale_coord',
terminalPaneKey: 'tab_coord:leaf_coord',
wait: true
})
)
})
it('rejects an empty --terminal instead of consuming the ambient mailbox', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_coord'
@@ -67,19 +49,4 @@ describe('orchestration check identity', () => {
).rejects.toMatchObject({ code: 'invalid_argument' })
expect(callMock).not.toHaveBeenCalled()
})
it('keeps an explicit legacy terminal handle scoped to that handle', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_stale_env'
await invokeCheck(new Map<string, string | boolean>([['terminal', 'term_legacy_worker']]))
expect(callMock).toHaveBeenCalledTimes(1)
expect(callMock).toHaveBeenCalledWith(
'orchestration.check',
expect.objectContaining({
terminal: 'term_legacy_worker',
terminalPaneKey: undefined
})
)
})
})
@@ -2,7 +2,7 @@ import { afterEach, expect, it, vi } from 'vitest'
const callMock = vi.fn()
const printResultMock = vi.hoisted(() => vi.fn())
vi.mock('../format', () => ({ printResult: printResultMock }))
vi.mock('../command-result-output', () => ({ printResult: printResultMock }))
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
@@ -13,57 +13,6 @@ afterEach(() => {
printResultMock.mockReset()
})
it('accepts an explicitly attested legacy worker-server settlement', async () => {
const result = {
relay: {
messageId: 'relay_legacy_done',
sequence: 1,
dispatchId: 'ctx_legacy',
destination: 'run_home',
accepted: true
},
lifecycle: {
action: 'completed',
authority: 'worker_server_legacy'
}
}
callMock.mockResolvedValueOnce({ result })
await ORCHESTRATION_HANDLERS['orchestration send'](
orchestrationTestContext(
callMock,
new Map<string, string | boolean>([
['full', true],
['from', 'term_worker'],
['subject', 'done'],
['type', 'worker_done'],
['task-id', 'task_legacy'],
['dispatch-id', 'ctx_legacy'],
['outcome', 'succeeded']
]),
true
)
)
expect(callMock).toHaveBeenCalledOnce()
expect(callMock).toHaveBeenCalledWith(
'orchestration.send',
expect.objectContaining({
from: 'term_worker',
subject: 'done',
type: 'worker_done',
payload: JSON.stringify({
taskId: 'task_legacy',
dispatchId: 'ctx_legacy',
outcome: 'succeeded'
}),
waitForLifecycleSettlement: true
}),
{ orchestrationRequestId: expect.any(String) }
)
expect(printResultMock).toHaveBeenCalledWith({ result }, true, expect.any(Function))
})
it('rejects an unattested relay settlement', async () => {
callMock.mockResolvedValueOnce({
result: {
@@ -2,10 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../format', () => ({ printResult: vi.fn() }))
vi.mock('../command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { ORCHESTRATION_HANDLERS } from './orchestration'
import { orchestrationTestContext } from './orchestration-handler-test-context'
@@ -161,35 +161,4 @@ describe('legacy orchestration CLI inspection', () => {
).toEqual(['[Reply: orca orchestration reply --id msg_current --body "..."]'])
expect(response.result.formatted).not.toContain('--from run:run_current')
})
it('labels legacy rows in full inbox output without hiding their body', async () => {
const result = {
messages: [
{
id: 'msg_legacy',
run_id: 'run_legacy_local',
from_handle: 'term_worker',
to_handle: 'term_coord',
subject: 'progress',
body: 'Tests are running.'
}
],
count: 1
}
callMock.mockResolvedValue({ result })
await ORCHESTRATION_HANDLERS['orchestration inbox'](
orchestrationTestContext(
callMock,
new Map<string, string | boolean>([['full', true]]),
false,
'/repo'
)
)
const formatter = vi.mocked(printResult).mock.calls[0]?.[2]
const output = formatter?.(result)
expect(output).toContain('msg_legacy [legacy, read-only]')
expect(output).toContain('Tests are running.')
})
})
@@ -1,5 +1,5 @@
import { afterEach, expect, it, vi } from 'vitest'
import { reportCliError } from '../format'
import { reportCliError } from '../cli-error'
import { ORCHESTRATION_HANDLERS } from './orchestration'
afterEach(() => {
@@ -2,10 +2,10 @@ import { afterEach, expect, it, vi } from 'vitest'
const callMock = vi.fn()
const originalExitCode = process.exitCode
vi.mock('../format', () => ({ printResult: vi.fn() }))
vi.mock('../command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { ORCHESTRATION_HANDLERS } from './orchestration'
afterEach(() => {
@@ -84,28 +84,6 @@ it('raises a Run-home relay rejection for the CLI error boundary', async () => {
expect(printResult).not.toHaveBeenCalled()
})
it('accepts an explicit current settlement without a compatibility read', async () => {
callMock.mockResolvedValueOnce({
result: { message: { id: 'msg_done' }, lifecycle: { action: 'completed' } }
})
await ORCHESTRATION_HANDLERS['orchestration send']({
flags: new Map([
['from', 'term_worker'],
['subject', 'done'],
['type', 'worker_done'],
['task-id', 'task_1'],
['dispatch-id', 'ctx_1'],
['outcome', 'succeeded']
]),
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)
expect(callMock).toHaveBeenCalledOnce()
})
it('fails closed when an older runtime leaves worker_done dispatched without a verdict', async () => {
callMock
.mockResolvedValueOnce({
@@ -200,129 +178,6 @@ it('preserves the worker_done mutation identity when post-verification fails', a
})
})
it('accepts a legacy response only after the authoritative dispatch is terminal', async () => {
callMock
.mockResolvedValueOnce({
result: { message: { id: 'msg_legacy_completed', run_id: 'run_1' } }
})
.mockResolvedValueOnce({
result: { dispatch: { id: 'ctx_1', status: 'completed' } }
})
.mockResolvedValueOnce({
result: {
tasks: [
{
id: 'task_1',
status: 'completed',
result: JSON.stringify({
provenance: 'worker_report',
messageId: 'msg_legacy_completed',
outcome: 'succeeded'
})
}
]
}
})
await ORCHESTRATION_HANDLERS['orchestration send']({
flags: new Map([
['from', 'term_worker'],
['subject', 'done'],
['type', 'worker_done'],
['task-id', 'task_1'],
['dispatch-id', 'ctx_1'],
['outcome', 'succeeded']
]),
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)
expect(callMock).toHaveBeenCalledTimes(3)
expect(callMock).toHaveBeenNthCalledWith(2, 'orchestration.dispatchShow', { task: 'task_1' })
})
it('accepts a legacy failed report only after the authoritative dispatch failed', async () => {
callMock
.mockResolvedValueOnce({
result: { message: { id: 'msg_legacy_failed', run_id: 'run_1' } }
})
.mockResolvedValueOnce({ result: { dispatch: { id: 'ctx_1', status: 'failed' } } })
.mockResolvedValueOnce({
result: {
tasks: [
{
id: 'task_1',
status: 'failed',
result: JSON.stringify({
provenance: 'worker_report',
messageId: 'msg_legacy_failed',
outcome: 'failed'
})
}
]
}
})
await ORCHESTRATION_HANDLERS['orchestration send']({
flags: new Map([
['from', 'term_worker'],
['subject', 'failed'],
['type', 'worker_done'],
['task-id', 'task_1'],
['dispatch-id', 'ctx_1'],
['outcome', 'failed']
]),
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)
expect(callMock).toHaveBeenCalledTimes(3)
})
it('accepts an idempotent retry whose first report already settled', async () => {
callMock
.mockResolvedValueOnce({
result: {
message: { id: 'msg_retry', run_id: 'run_1', from_handle: 'term_worker' }
}
})
.mockResolvedValueOnce({ result: { dispatch: { id: 'ctx_1', status: 'completed' } } })
.mockResolvedValueOnce({
result: {
tasks: [
{
id: 'task_1',
status: 'completed',
result: JSON.stringify({
provenance: 'worker_report',
messageId: 'msg_first',
reportedBy: 'term_worker',
outcome: 'succeeded'
})
}
]
}
})
await ORCHESTRATION_HANDLERS['orchestration send']({
flags: new Map([
['from', 'term_worker'],
['subject', 'done'],
['type', 'worker_done'],
['task-id', 'task_1'],
['dispatch-id', 'ctx_1'],
['outcome', 'succeeded']
]),
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)
expect(callMock).toHaveBeenCalledTimes(3)
})
it('rejects an unrelated failed Dispatch that left its Task blocked', async () => {
callMock
.mockResolvedValueOnce({
@@ -2,10 +2,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../format', () => ({ printResult: vi.fn() }))
vi.mock('../command-result-output', () => ({ printResult: vi.fn() }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { okFixture } from '../test-fixtures'
import { RuntimeClient } from '../runtime-client'
@@ -57,17 +57,4 @@ describe('orchestration task-list brief output', () => {
expect(response).toHaveProperty('result.tasks.0.spec', `First line ${'detail '.repeat(21)}d…`)
expect(response).toHaveProperty('result.tasks.0.spec_truncated', true)
})
it('passes server-abbreviated rows through untouched', async () => {
const serverTasks = [
{ id: 'task_1', spec: 'already brief…', status: 'ready', spec_truncated: true }
]
const serverResponse = okFixture('req_tasks', { tasks: serverTasks, count: 1 })
callMock.mockReset().mockResolvedValue(serverResponse)
const response = await runTaskListBrief()
// Re-abbreviating would reset spec_truncated because the already-truncated text fits the cap.
expect(response).toHaveProperty('result.tasks', serverTasks)
})
})
@@ -2,14 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
const originalExitCode = process.exitCode
vi.mock('../format', async (importOriginal) => {
vi.mock('../command-result-output', async (importOriginal) => {
const original = await importOriginal<{ printResult: typeof printResult }>()
return { printResult: vi.fn(original.printResult) }
})
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { RuntimeClient } from '../runtime-client'
+2 -2
View File
@@ -4,12 +4,12 @@ const callMock = vi.fn()
const getTerminalHandleMock = vi.hoisted(() => vi.fn())
const originalExitCode = process.exitCode
vi.mock('../format', () => ({ printResult: vi.fn() }))
vi.mock('../command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
import { printResult } from '../format'
import { printResult } from '../command-result-output'
import { okFixture } from '../test-fixtures'
beforeEach(() => {
+1 -1
View File
@@ -1,5 +1,5 @@
import type { HandlerContext } from '../../dispatch'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { formatOrchestrationErrorLine } from '../../cli-error'
import { renderCommand } from '../../orchestration-mutation-recovery'
import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command'
@@ -1,5 +1,5 @@
import type { CommandHandler } from '../../dispatch'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { printOrchestrationResult } from './agent-view'
import { getOptionalJsonFlag, getOptionalStringFlag, getRequiredStringFlag } from '../../flags'
import { callOrchestrationMutation } from './mutation-request'
@@ -1,6 +1,6 @@
import type { CommandHandler } from '../../dispatch'
import { refuseAgentServerRoute } from './agent-server-route'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { withReceiptNext } from './receipt-next-text'
import { printOrchestrationResult } from './agent-view'
import { checkView } from './message-agent-views'
@@ -1,5 +1,5 @@
import type { CommandHandler } from '../../dispatch'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import {
getOptionalPositiveIntegerFlag,
getOptionalStringFlag,
@@ -1,5 +1,5 @@
import type { CommandHandler } from '../../dispatch'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { printOrchestrationResult } from './agent-view'
import { withReceiptNext } from './receipt-next-text'
import { formatWorkerStart } from './worker-output'
@@ -1,6 +1,6 @@
import type { CommandHandler } from '../../dispatch'
import { getOptionalStringFlag } from '../../flags'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { renderCommand } from '../../orchestration-mutation-recovery'
import { RuntimeClientError, type RuntimeClient } from '../../runtime-client'
import type { RuntimeStatus } from '../../../shared/runtime-types'
@@ -1,6 +1,6 @@
import { abbreviateOrchestrationText } from '../../../shared/orchestration/orchestration-task-summary'
import type { CommandHandler } from '../../dispatch'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { printOrchestrationResult } from './agent-view'
import {
getOptionalPositiveIntegerFlag,
@@ -1,5 +1,5 @@
import type { CommandHandler } from '../../dispatch'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { printOrchestrationResult } from './agent-view'
import { TASK_LIST_VIEW, TASK_RECEIPT_VIEW, type TaskListResult } from './task-agent-views'
import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags'
@@ -1,5 +1,5 @@
import type { CommandHandler } from '../../dispatch'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { withReceiptNext } from './receipt-next-text'
import { getOptionalStringFlag, getPresentStringFlag } from '../../flags'
import { RuntimeClientError, type RuntimeClient } from '../../runtime-client'
@@ -1,5 +1,5 @@
import type { CommandHandler } from '../../dispatch'
import { printResult } from '../../format'
import { printResult } from '../../command-result-output'
import { printOrchestrationReceipt, printOrchestrationResult } from './agent-view'
import { WORKER_SHOW_VIEW, type WorkerShowResult } from './worker-agent-views'
import {

Some files were not shown because too many files have changed in this diff Show More