test: remove 133 low-value workflow, mobile and CLI tests (#38725)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-05 15:52:52 -08:00
committed by GitHub
co-authored by OrcaWin
parent 3dd9a49e93
commit 5bc786c1a7
20 changed files with 9 additions and 2869 deletions
+2 -8
View File
@@ -12952,7 +12952,7 @@
"providers": ["local", "daemon", "ssh", "remote-runtime"],
"coveredPlatforms": ["macos", "windows"],
"coveredProviders": ["local"],
"coverageNotes": "Source-built macOS and physical Windows Electron journeys cover the public CLI through RPC, runtime identity, real PTY/ConPTY writes, and a delayed fake Codex composer. Focused units cover CLI intent, fresh Claude/Codex foreground identity, framing bytes, stale-agent shell fallback, and exact legacy behavior for every other configured agent. SSH, daemon, and remote-runtime remain explicit gaps. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/rpc/terminal-agent-prompt-send.test.ts reduced. Lose mocked successful routing, fallback args and signal identity forwarding. Retained fake PTY write sink observes no output; no actual shell/provider claimed. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.",
"coverageNotes": "Audit1586 removes mock-only terminal prompt forwarding and capability assertions without equivalent replacement coverage. Retained CLI tests cover unverified close failures and a missing prompt receipt after preflight using injected host responses; they do not establish actual PTY delivery, host restart or durable replay. Assertion references selecting removed alarms are retired; unaffected execution receipts remain unchanged. Historical scope before this audit: Source-built macOS and physical Windows Electron journeys cover the public CLI through RPC, runtime identity, real PTY/ConPTY writes, and a delayed fake Codex composer. Focused units cover CLI intent, fresh Claude/Codex foreground identity, framing bytes, stale-agent shell fallback, and exact legacy behavior for every other configured agent. SSH, daemon, and remote-runtime remain explicit gaps. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/rpc/terminal-agent-prompt-send.test.ts reduced. Lose mocked successful routing, fallback args and signal identity forwarding. Retained fake PTY write sink observes no output; no actual shell/provider claimed. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.",
"motivatingLinks": [
"https://linear.app/stably/issue/STA-4328",
"https://github.com/stablyai/orca/issues/14525"
@@ -12975,13 +12975,6 @@
"tests/tools/repro-terminal-send-submit.mjs"
],
"assertionRefs": [
{
"file": "src/cli/handlers/terminal.test.ts",
"assertions": [
"combined text and Enter carries explicit agent-prompt intent",
"text-only and bare Enter remain direct terminal input"
]
},
{
"file": "tests/e2e/terminal-send-agent-prompt-submit.spec.ts",
"assertions": [
@@ -13041,6 +13034,7 @@
"Retain mixed-version evidence that old hosts strip the optional intent and new hosts accept old clients without a protocol bump."
],
"knownGaps": [
"Audit1586 removes mock-only terminal prompt forwarding and capability assertions without equivalent replacement coverage. Retained CLI tests cover unverified close failures and a missing prompt receipt after preflight using injected host responses; they do not establish actual PTY delivery, host restart or durable replay. Assertion references selecting removed alarms are retired; unaffected execution receipts remain unchanged.",
"Live SSH/daemon/remote-runtime evidence is not yet attached.",
"Only Claude and Codex opt into settlement; every other agent retains the legacy behavior until independently validated.",
"A new CLI talking to an old host safely loses the optional field and therefore keeps the old timing behavior until the host updates.",
@@ -33,7 +33,6 @@
"config/scripts/preflight/changed-checks/check-changed-pass-cache.test.mjs": 184,
"config/scripts/static-analysis/process-boundaries/check-compat-boundary-imports.test.mjs": 145,
"config/scripts/daemon-protocol/admission/check-daemon-protocol-crossing.test.mjs": 180,
"config/scripts/typecheck/e2e-admission/check-e2e-typecheck-ratchet.test.mjs": 94,
"config/scripts/static-analysis/ratchets/test-quality/check-flaky-test-pattern-ratchet.test.mjs": 151,
"config/scripts/static-analysis/ratchets/renderer-state/check-focus-read-ratchet.test.mjs": 79,
"config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.test.mjs": 149,
@@ -207,12 +206,9 @@
"config/scripts/desktop-build/output-contracts/plain-node-entry-guard.test.ts": 710,
"config/scripts/ci/e2e-selection/playwright-focused-workflow-selection.test.mjs": 1565,
"config/scripts/tool-invocation/pnpm-cli-invocation.test.mjs": 65,
"config/scripts/workflow/pr-admission/pr-aggregate-gate.test.mjs": 236,
"config/scripts/ci/workflow-contracts/pr-auxiliary-preflight-admission.test.mjs": 2174,
"config/scripts/workflow/source-routing/pr-code-change-scope-cross-version-launch-route.test.mjs": 54,
"config/scripts/workflow/source-routing/pr-code-change-scope-cross-version-send-path.test.mjs": 71,
"config/scripts/workflow/source-routing/pr-code-change-scope-format-route.test.mjs": 155,
"config/scripts/workflow/source-routing/pr-code-change-scope-released-phone.test.mjs": 76,
"config/scripts/workflow/source-routing/pr-code-change-scope.test.mjs": 403,
"config/scripts/workflow/source-routing/pr-codex-unit-only-selection.test.mjs": 53,
"config/scripts/workflow/source-routing/pr-e2e-gate-contract.test.mjs": 270,
@@ -229,7 +225,6 @@
"config/scripts/localization/catalog-validation/protected-copy-keys.test.mjs": 394,
"config/scripts/diagnostics/terminal-transcripts/pty-transcript-secret-scan.test.mjs": 188,
"config/scripts/release/publication/publish-complete-draft-releases.test.mjs": 261,
"config/scripts/workflow/pr-admission/pullfrog-review-scope.test.mjs": 50,
"config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs": 225,
"config/scripts/release/workflow-contracts/qualified-orcad-template.test.mjs": 555,
"config/scripts/static-analysis/ratchet-baseline/ratchet-baseline.test.mjs": 66,
@@ -242,7 +237,6 @@
"config/scripts/worktree-storage/reclaim-release-test-caches.test.ts": 331,
"config/scripts/worktree-storage/reclaim-vite-caches.test.mjs": 442,
"config/scripts/worktree-storage/reclaim-vitest-module-caches.test.mjs": 109,
"config/scripts/worktree-storage/reclaim-worktree-command.test.mjs": 100,
"config/scripts/worktree-storage/reclaim-worktree-generated-files.test.mjs": 3376,
"config/scripts/worktree-storage/reclaim-worktree-space.test.mjs": 2469,
"config/scripts/release/workflow-contracts/release-cut-token-permissions.test.mjs": 276,
@@ -343,7 +337,6 @@
"src/cli/computer-format.test.ts": 135,
"src/cli/computer-tree-query.test.ts": 79,
"src/cli/emulator-logcat-format.test.ts": 69,
"src/cli/execution-host-flag.test.ts": 113,
"src/cli/format-recovery.test.ts": 413,
"src/cli/format.test.ts": 446,
"src/cli/handler-group-manifest.test.ts": 3610,
@@ -415,7 +408,6 @@
"src/cli/index-agent-launch.test.ts": 594,
"src/cli/index-automation-run-output.test.ts": 513,
"src/cli/index-automation-setup.test.ts": 466,
"src/cli/index-automation-target.test.ts": 511,
"src/cli/index-environment-commands.test.ts": 351,
"src/cli/index-file-open-headless.test.ts": 291,
"src/cli/index-jira.test.ts": 435,
@@ -1,59 +0,0 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { countTestTypeErrors, main } from './check-e2e-typecheck-ratchet.mjs'
const OUTPUT = [
"tests/e2e/a.spec.ts(22,10): error TS2305: Module './helpers/flow' has no exported member 'convertThenRetire'.",
"tests/e2e/a.spec.ts(30,1): error TS2339: Property 'x' does not exist on type 'Y'.",
"tests/e2e/helpers/b.ts(5,3): error TS2322: Type 'string' is not assignable to type 'number'.",
"cloud/apps/relay/src/app.ts(18,8): error TS2307: Cannot find module '@orca-cloud/relay-contract'.",
' Continuation line of a multi-line diagnostic.'
].join('\n')
describe('countTestTypeErrors', () => {
it('counts tests/ errors per file and ignores rows from other workspaces', () => {
expect(countTestTypeErrors(OUTPUT)).toEqual(
new Map([
['tests/e2e/a.spec.ts', 2],
['tests/e2e/helpers/b.ts', 1]
])
)
})
it('reads CRLF output', () => {
expect(countTestTypeErrors(OUTPUT.replaceAll('\n', '\r\n')).get('tests/e2e/a.spec.ts')).toBe(2)
})
})
describe('main', () => {
let root = ''
afterEach(() => {
fs.rmSync(root, { recursive: true, force: true })
vi.restoreAllMocks()
})
function withBaseline(text) {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'e2e-typecheck-ratchet-'))
fs.mkdirSync(path.join(root, 'config'))
fs.writeFileSync(path.join(root, 'config/e2e-typecheck-baseline.txt'), text)
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'log').mockImplementation(() => {})
}
it('fails when a file gains an error, as a missing helper import does', () => {
withBaseline('1 tests/e2e/a.spec.ts\n1 tests/e2e/helpers/b.ts\n')
expect(main(root, undefined, OUTPUT)).toBe(1)
})
it('passes at the baseline and fails until a fixed file is pruned', () => {
withBaseline('2 tests/e2e/a.spec.ts\n1 tests/e2e/helpers/b.ts\n')
expect(main(root, undefined, OUTPUT)).toBe(0)
const fixed = OUTPUT.replace(/^tests\/e2e\/helpers\/b\.ts.*$/m, '')
expect(main(root, undefined, fixed)).toBe(1)
expect(main(root, '--prune', fixed)).toBe(0)
expect(main(root, undefined, fixed)).toBe(0)
})
})
@@ -1,72 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
aggregateJob,
aggregateNeeds,
aggregateRequiredJobs,
aggregateSelectors,
aggregateShell,
aggregateShouldRun,
aggregateWorkflow,
compileAggregateExpression
} from './pr-aggregate-gate-context.mjs'
const results = ['success', 'failure', 'cancelled', 'skipped', '', 'unknown', undefined, null]
const admitted = (needs, cancelled = false) =>
aggregateShouldRun(
{ needs, github: { event: { pull_request: { draft: false } } } },
cancelled
).coerceString() === 'true'
describe('explicit PR aggregate result', () => {
it('keeps every required dependency and the existing failure reporter', () => {
expect(aggregateJob.name).toBe('PR checks passed')
expect(aggregateJob.needs).toEqual([
'code_paths',
'preflight',
...aggregateSelectors.filter((job) => job !== 'static_analysis' && job !== 'typecheck')
])
for (const job of ['e2e', 'terminal_ime_native', 'windows_wsl', 'unit_selection_evidence']) {
expect(aggregateJob.needs).not.toContain(job)
}
expect(aggregateJob['continue-on-error']).toBeUndefined()
expect(aggregateShell['continue-on-error']).toBeUndefined()
expect(aggregateShell.run).toContain('"$CODE_PATHS" != "success"')
const checked = [...aggregateShell.run.matchAll(/^check_job (\S+) /gm)].map((match) => match[1])
expect(checked).toEqual(aggregateRequiredJobs)
})
it('runs for code, docs, reused and mixed plans after every dependency outcome', () => {
for (const selected of ['true', 'false']) {
const plan = aggregateNeeds(selected)
expect(admitted(plan)).toBe(true)
for (const job of aggregateJob.needs) {
for (const result of results) {
const needs = aggregateNeeds(selected)
needs[job].result = result
expect(admitted(needs), `${selected}/${job}/${result}`).toBe(true)
expect(admitted(needs, true), `${selected}/${job}/${result}`).toBe(false)
}
const missing = aggregateNeeds(selected)
delete missing[job]
expect(admitted(missing), `${selected}/${job}/missing`).toBe(true)
expect(admitted(missing, true), `${selected}/${job}/missing`).toBe(false)
}
}
expect(admitted(aggregateNeeds('false', { test: 'true', typecheck: 'true' }))).toBe(true)
expect(admitted({})).toBe(true)
expect(admitted({}, true)).toBe(false)
})
it('passes raw preflight selectors to the shell before case-insensitive Actions comparisons', () => {
const outputs = aggregateWorkflow.jobs.code_paths.outputs
for (const [variable, output] of [
['STATIC_ANALYSIS_SHOULD_RUN', 'static_analysis'],
['TYPECHECK_SHOULD_RUN', 'typecheck']
]) {
expect(aggregateShell.env[variable]).toBe(`\${{ needs.code_paths.outputs.${output} }}`)
expect(outputs[output]).toContain(`steps.filter.outputs.${output}`)
}
const compare = compileAggregateExpression("needs.value == 'true'")
expect(compare({ needs: { value: 'TRUE' } }).coerceString()).toBe('true')
})
})
@@ -58,28 +58,6 @@ const outcomes = ['success', 'skipped', 'failure', 'cancelled', '', 'unknown', u
describe.skipIf(process.platform === 'win32')(
'required PR checks through the real aggregate shell',
() => {
it('accepts code, docs, reuse and mixed plans with their required outcomes', async () => {
const plans = [aggregateNeeds('true'), aggregateNeeds('false')]
for (const static_analysis of ['true', 'false']) {
for (const typecheck of ['true', 'false']) {
plans.push(aggregateNeeds('false', { static_analysis, typecheck }))
}
}
plans.push(aggregateNeeds('false', { test: 'true', package: 'true', typecheck: 'true' }))
for (const should_run of ['true', 'false', ...malformedSelectors]) {
plans.push(aggregateNeeds('true', { should_run }))
}
for (const needs of plans) {
const { static_analysis, typecheck } = needs.code_paths.outputs
expect(needs.preflight.result).toBe(
static_analysis === 'true' || typecheck === 'true' ? 'success' : 'skipped'
)
}
expect(await verifyCases(plans.map(aggregateEnvironment), gate.run)).toEqual(
plans.map(() => 0)
)
})
it('rejects missing, failed, cancelled or incorrectly skipped required results', async () => {
const cases = []
const expected = []
@@ -113,22 +91,5 @@ describe.skipIf(process.platform === 'win32')(
}
expect(await verifyCases(cases, gate.run)).toEqual(cases.map(() => 1))
})
it('rejects malformed preflight phases even when the other phase selects preflight', async () => {
const cases = []
for (const phase of ['static_analysis', 'typecheck']) {
const other = phase === 'static_analysis' ? 'typecheck' : 'static_analysis'
for (const selected of malformedSelectors) {
for (const otherSelected of ['true', 'false']) {
for (const result of ['success', 'skipped']) {
const needs = aggregateNeeds('false', { [phase]: selected, [other]: otherSelected })
needs.preflight.result = result
cases.push(aggregateEnvironment(needs))
}
}
}
}
expect(await verifyCases(cases, gate.run)).toEqual(cases.map(() => 1))
})
}
)
@@ -1,109 +0,0 @@
import { expect, it, vi } from 'vitest'
import scope from './pullfrog-review-scope.cjs'
it('groups a current review by PR while leaving other agent tasks independent', async () => {
const get = vi.fn(async () => ({ data: { state: 'open', head: { sha: 'current' } } }))
const core = { setOutput: vi.fn(), warning: vi.fn() }
const context = {
repo: { owner: 'stablyai', repo: 'orca' },
runId: 7,
payload: { inputs: { name: 'Review #42 [abc]' } }
}
const github = {
rest: {
pulls: { get },
actions: { listWorkflowRuns: async () => ({ data: { workflow_runs: [] } }) }
}
}
await scope.reviewScope({ core, context, github })
expect(get).toHaveBeenCalledWith({ owner: 'stablyai', repo: 'orca', pull_number: 42 })
expect(core.setOutput).toHaveBeenCalledWith('head', 'current')
get.mockClear()
await scope.reviewScope({
core,
github,
context: { ...context, payload: { inputs: { name: 'Investigate #42' } } }
})
expect(get).not.toHaveBeenCalled()
expect(core.setOutput).toHaveBeenLastCalledWith('current', 'true')
})
it('coalesces only explicit or recognized PR review identities', () => {
expect(scope.reviewNumber({ name: 'Review #23532 [85jpk]' })).toBe(23532)
expect(scope.reviewNumber({ name: 'Review new commits on #22727 [24lpq]' })).toBe(22727)
expect(scope.reviewNumber({ pull_request_number: '123' })).toBe(123)
for (const name of ['Fix #123', 'Review #12; echo test', 'Review #123', '', 'Review #0 [abc]']) {
expect(scope.reviewNumber({ name })).toBeNull()
}
})
it('skips closed or explicitly stale reviews and tolerates lookup failure', async () => {
for (const data of [
{ state: 'closed', head: { sha: 'a' } },
{ state: 'open', head: { sha: 'b' } }
]) {
const core = { setOutput: vi.fn(), warning: vi.fn() }
await scope.reviewScope({
core,
context: {
repo: {},
runId: 1,
payload: { inputs: { pull_request_number: '1', head_sha: 'a' } }
},
github: { rest: { pulls: { get: async () => ({ data }) } } }
})
expect(core.setOutput).toHaveBeenCalledWith('current', 'false')
}
const core = { setOutput: vi.fn(), warning: vi.fn() }
await scope.reviewScope({
core,
context: { repo: {}, runId: 2, payload: { inputs: { pull_request_number: '1' } } },
github: {
rest: {
pulls: {
get: async () => {
throw new Error('offline')
}
}
}
}
})
expect(core.setOutput).toHaveBeenCalledWith('current', 'true')
expect(core.warning).toHaveBeenCalled()
})
it('a delayed older scope cannot cancel or replace a newer review', async () => {
const runs = [
{ id: 6, display_title: 'Review #42 [a]', status: 'in_progress' },
{ id: 8, display_title: 'Custom review | PR 42', status: 'queued' },
{ id: 5, display_title: 'Investigate #42', status: 'in_progress' },
{ id: 4, display_title: 'Review #43 [other]', status: 'in_progress' }
]
for (const runId of [7, 9]) {
const cancelWorkflowRun = vi.fn(async () => ({}))
const core = { setOutput: vi.fn(), warning: vi.fn() }
await scope.reviewScope({
context: {
repo: { owner: 'stablyai', repo: 'orca' },
runId,
payload: { inputs: { name: 'Review #42 [current]' } }
},
core,
github: {
rest: {
pulls: { get: async () => ({ data: { state: 'open', head: { sha: 'head' } } }) },
actions: {
listWorkflowRuns: async () => ({ data: { workflow_runs: runs } }),
cancelWorkflowRun
}
}
}
})
if (runId === 7) {
expect(cancelWorkflowRun).not.toHaveBeenCalled()
expect(core.setOutput).toHaveBeenCalledWith('current', 'false')
} else {
expect(cancelWorkflowRun.mock.calls.map(([args]) => args.run_id)).toEqual([6, 8])
}
}
})
@@ -1,27 +0,0 @@
import { readFileSync } from 'node:fs'
import { expect, it } from 'vitest'
import { parse } from 'yaml'
import { classifyPrJobs } from './pr-code-change-scope.mjs'
// Whole-tree formatting must run on every formatted-file change or drift breaks later PR merge refs.
it.each(['README.md', '.github/ISSUE_TEMPLATE/bug.yml', '.github/workflows/mobile.yml'])(
'runs static analysis, and only it, for a %s diff the formatter reads',
(file) => {
expect(classifyPrJobs([file])).toMatchObject({
should_run: false,
static_analysis: true,
typecheck: false,
test: false
})
}
)
it('leaves paths the formatter ignores out of static analysis', () => {
expect(classifyPrJobs(['cloud/apps/relay/README.md']).static_analysis).toBe(false)
expect(classifyPrJobs(['docs/assets/logo.png']).static_analysis).toBe(false)
})
it('checks out the formatter config the detector reads its ignores from', () => {
const workflow = parse(readFileSync('.github/workflows/pr.yml', 'utf8'))
expect(workflow.jobs.code_paths.steps[0].with['sparse-checkout']).toContain('/.oxfmtrc.json')
})
@@ -1,19 +0,0 @@
import { expect, it } from 'vitest'
import { classifyPrJobs } from './pr-code-change-scope.mjs'
it('runs the released phone contract for its current discovery dependencies', () => {
for (const file of [
'src/main/native-chat/agent-model-catalog/agent-model-catalog-entry.ts',
'src/main/native-chat/agent-model-catalog/agent-model-catalog-store.ts',
'src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts',
'src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts',
'src/main/native-chat/agent-model-catalog/agent-model-catalog-listing-waiters.ts',
'src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.ts',
'src/main/claude/claude-model-catalog-probe.ts'
]) {
expect(classifyPrJobs([file])['cross-version-wire'], file).toBe(true)
}
expect(
classifyPrJobs(['mobile/src/transport/rpc-client-request-tracker.ts'])['cross-version-wire']
).toBe(false)
})
@@ -2,10 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
import {
createWorkspaceSourceResolver,
workspacePackageManifests
} from './workspace-source-exports.mjs'
import { createWorkspaceSourceResolver } from './workspace-source-exports.mjs'
const temporary = []
afterEach(() => {
@@ -49,20 +46,6 @@ const publicExports = {
}
}
it('inventories every declared package manifest without requiring built or source exports', () => {
const root = fixture({
patterns: ['src/packages/*', 'native/windows-registry'],
extra: {
'native/windows-registry/package.json': JSON.stringify({ name: '@orca/windows-registry' }),
'mobile/packages/model/package.json': JSON.stringify({ name: '@orca/mobile-model' })
}
})
expect(workspacePackageManifests(root)).toEqual([
'native/windows-registry/package.json',
'src/packages/process-host/package.json'
])
})
it('maps only explicit public source exports with exact aliases independent of compiled output', () => {
const resolver = createWorkspaceSourceResolver(fixture({ exports: publicExports }))
expect(resolver.resolve('@orca/process-host')).toMatchObject({
@@ -89,21 +72,6 @@ it('maps only explicit public source exports with exact aliases independent of c
expect(resolver.resolve('zod')).toBeNull()
})
it.each(['@orca/unknown', '@orca/process-host/private', '@orca/process-host/src/run-process'])(
'rejects unknown and private internal imports: %s',
(specifier) => {
const resolver = createWorkspaceSourceResolver(fixture({ exports: publicExports }))
expect(() => resolver.resolve(specifier)).toThrow('No public orca-source export')
}
)
it('requires source metadata instead of trusting a public built export', () => {
const resolver = createWorkspaceSourceResolver(
fixture({ exports: { '.': './dist/run-process.js' } })
)
expect(() => resolver.resolve('@orca/process-host')).toThrow('No public orca-source export')
})
it('respects excluded workspace packages and independent workspaces', () => {
const root = fixture({
exports: publicExports,
@@ -120,40 +88,3 @@ it('respects excluded workspace packages and independent workspaces', () => {
expect(() => resolver.resolve('@orca/process-host')).toThrow('No public orca-source export')
expect(() => resolver.resolve('@orca/mobile-model')).toThrow('No public orca-source export')
})
it('retains deliberately external native workspace packages', () => {
const root = fixture({
patterns: ['native/windows-registry'],
extra: {
'native/windows-registry/package.json': JSON.stringify({
name: '@orca/windows-registry',
main: 'index.js'
})
}
})
expect(createWorkspaceSourceResolver(root).resolve('@orca/windows-registry')).toBeNull()
})
it.each([
'../outside.ts',
'./dist/run-process.js',
'./src/missing.ts',
'./src/../src/run-process.ts',
'./src/run-process.d.ts'
])('rejects unsafe, stale or missing source targets: %s', (target) => {
const root = fixture({ exports: { '.': { 'orca-source': target } } })
expect(() => createWorkspaceSourceResolver(root)).toThrow()
})
it('rejects wildcard source exports and duplicate workspace identities', () => {
expect(() =>
createWorkspaceSourceResolver(
fixture({ exports: { './*': { 'orca-source': './src/run-process.ts' } } })
)
).toThrow('must name public entry points')
const root = fixture({
exports: publicExports,
extra: { 'src/packages/duplicate/package.json': JSON.stringify({ name: '@orca/process-host' }) }
})
expect(() => createWorkspaceSourceResolver(root)).toThrow('duplicate workspace package name')
})
@@ -1,94 +0,0 @@
import { PassThrough } from 'node:stream'
import { expect, it, vi } from 'vitest'
import { runReclaimCommand } from './reclaim-worktree-command.mjs'
function terminal(answer, tty = true) {
const input = new PassThrough()
const output = new PassThrough()
input.isTTY = tty
output.isTTY = tty
let text = ''
output.on('data', (chunk) => {
text += chunk.toString()
if (chunk.toString().includes('[y/N]')) {
input.write(`${answer}\n`)
}
})
return { input, output, text: () => text }
}
it.each(['Y', 'y', 'yes', ' YES '])(
'applies after preview when the user answers %j',
async (answer) => {
const streams = terminal(answer)
const reclaim = vi.fn().mockResolvedValue({ completed: true })
await runReclaimCommand(
['--tests-stopped', '--release-cache-min-age-days', '7', '--generated-min-age-days', '3'],
{ ...streams, reclaim }
)
expect(reclaim.mock.calls.map(([options]) => options.apply)).toEqual([false, true])
expect(reclaim.mock.calls[1][0]).toMatchObject({
testsStopped: true,
releaseCacheMinAgeDays: 7,
generatedMinAgeDays: 3
})
}
)
it.each(['', 'n', 'no', 'sure'])('leaves files alone after preview on %j', async (answer) => {
const streams = terminal(answer)
const reclaim = vi.fn().mockResolvedValue({ completed: true })
await runReclaimCommand([], { ...streams, reclaim })
expect(reclaim).toHaveBeenCalledTimes(1)
expect(reclaim.mock.calls[0][0].apply).toBe(false)
})
it.each(['--apply', '--automatic'])('never prompts with %s', async (flag) => {
const streams = terminal('Y')
const reclaim = vi.fn().mockResolvedValue({ completed: true })
await runReclaimCommand([flag], { ...streams, reclaim })
expect(reclaim).toHaveBeenCalledTimes(1)
expect(streams.text()).not.toContain('[y/N]')
})
it('does not interpret piped input as approval', async () => {
const streams = terminal('Y', false)
streams.input.write('Y\n')
const reclaim = vi.fn().mockResolvedValue({ completed: true })
await runReclaimCommand([], { ...streams, reclaim })
expect(reclaim).toHaveBeenCalledTimes(1)
expect(reclaim.mock.calls[0][0].apply).toBe(false)
expect(streams.text()).not.toContain('[y/N]')
})
it('does not offer to apply a failed preview', async () => {
const streams = terminal('Y')
const reclaim = vi.fn().mockRejectedValue(new Error('preview failed'))
await expect(runReclaimCommand([], { ...streams, reclaim })).rejects.toThrow('preview failed')
expect(streams.text()).not.toContain('[y/N]')
})
it.each([
['--repo'],
['--repo', '--apply'],
['--exclude-worktree'],
['--release-cache-min-age-days'],
['--release-cache-min-age-days', 'NaN'],
['--release-cache-min-age-days', '-1'],
['--generated-min-age-days'],
['--generated-min-age-days', 'NaN'],
['--generated-min-age-days', '-1'],
['--unknown']
])('rejects invalid flags before any sweep: %j', async (...args) => {
const reclaim = vi.fn()
await expect(runReclaimCommand(args, { reclaim })).rejects.toThrow()
expect(reclaim).not.toHaveBeenCalled()
})
it('shows the single command without starting cleanup for help', async () => {
const streams = terminal('Y')
const reclaim = vi.fn()
await runReclaimCommand(['--help'], { ...streams, reclaim })
expect(streams.text()).toContain('pnpm reclaim-space')
expect(reclaim).not.toHaveBeenCalled()
})
@@ -258,21 +258,6 @@ it('retains a replacement directory introduced while the final Git check is runn
expect(await readFile(join(saved, 'generated.txt'), 'utf8')).toBe('generated bytes')
})
it('supports a retention override and rejects invalid ages', async () => {
const f = await fixture()
const file = await generated(f.sibling, 'mobile/node_modules', 2)
await reclaimWorktreeGeneratedFiles({
repoRoot: f.repoRoot,
apply: true,
generatedMinAgeDays: 1,
report: () => {}
})
await expect(lstat(file)).rejects.toMatchObject({ code: 'ENOENT' })
await expect(
reclaimWorktreeGeneratedFiles({ repoRoot: f.repoRoot, generatedMinAgeDays: Number.NaN })
).rejects.toThrow('--generated-min-age-days')
})
it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(
'reclaims read-only generated directories without chmodding hardlinked package files',
async () => {
@@ -1,58 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { act, create } from 'react-test-renderer'
import { ActionSheetModal } from '../components/ActionSheetModal'
import { openExternalLink } from '../platform/external-link'
import { triggerError, triggerSuccess } from '../platform/haptics'
import { MobileLinkActionSheet } from './MobileLinkActionSheet'
const writeText = vi.fn<(text: string) => Promise<void>>()
vi.mock('../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' }))
vi.mock('../platform/external-link', () => ({ openExternalLink: vi.fn() }))
vi.mock('../platform/clipboard', () => ({ useClipboardWriter: () => ({ writeText }) }))
vi.mock('../platform/haptics', () => ({ triggerSuccess: vi.fn(), triggerError: vi.fn() }))
const URL = 'https://example.com/docs'
function sheetActions(openInOrca?: (url: string) => void) {
let renderer!: ReturnType<typeof create>
act(() => {
renderer = create(<MobileLinkActionSheet url={URL} onClose={vi.fn()} openInOrca={openInOrca} />)
})
const actions: { id: string; onPress: () => void }[] =
renderer.root.findByType(ActionSheetModal).props.actions
return actions
}
describe('MobileLinkActionSheet', () => {
it('hands the tapped URL to the Orca browser, the phone browser and the clipboard', async () => {
const openInOrca = vi.fn()
writeText.mockResolvedValueOnce()
const actions = sheetActions(openInOrca)
expect(actions.map((action) => action.id)).toEqual(['openInOrca', 'openInBrowser', 'copyLink'])
actions[0]?.onPress()
actions[1]?.onPress()
await act(async () => actions[2]?.onPress())
expect(openInOrca).toHaveBeenCalledWith(URL)
expect(openExternalLink).toHaveBeenCalledWith(URL)
expect(writeText).toHaveBeenCalledWith(URL)
expect(triggerSuccess).toHaveBeenCalledTimes(1)
})
it("offers only the phone's choices where an Orca browser tab cannot open", () => {
expect(sheetActions().map((action) => action.id)).toEqual(['openInBrowser', 'copyLink'])
})
it('does not claim a copy the clipboard refused', async () => {
vi.mocked(triggerSuccess).mockClear()
writeText.mockRejectedValueOnce(new Error('Clipboard unavailable'))
const actions = sheetActions()
await act(async () => actions.at(-1)?.onPress())
expect(triggerError).toHaveBeenCalledTimes(1)
expect(triggerSuccess).not.toHaveBeenCalled()
})
})
@@ -88,23 +88,6 @@ describe('mobile native-chat draft persistence', () => {
])
})
it('never brings back a sent draft', async () => {
vi.useFakeTimers()
await loadMobileNativeChatDrafts('host-1', 'wt-1')
editMobileNativeChatDraft(TAB_A, 'ship it')
await settle()
clearMobileNativeChatDraftForSend(
TAB_A,
readMobileNativeChatDraftEditGeneration(TAB_A),
'ship it'
)
await writesSettled()
await relaunch()
expect(draftText(TAB_A)).toBe('')
})
it('keeps a send made before the saved drafts finished loading', async () => {
vi.useFakeTimers()
await loadMobileNativeChatDrafts('host-1', 'wt-1')
@@ -1,78 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, expect, it, vi } from 'vitest'
import { MobileNativeChatOpenFileContext } from '../mobile-native-chat-open-file-context'
import { MobileNativeChatQuestion } from './MobileNativeChatQuestion'
vi.mock('react-native', () => ({
Linking: { openURL: () => Promise.resolve() },
Platform: { OS: 'ios', select: (o: Record<string, unknown>) => o.ios },
Pressable: 'Pressable',
ScrollView: 'ScrollView',
StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
Text: 'Text',
View: 'View'
}))
vi.mock('lucide-react-native', () => ({
Check: 'Check',
ChevronDown: 'ChevronDown',
CircleHelp: 'CircleHelp',
X: 'X'
}))
vi.mock('../../../components/composer-input/MessageBox', () => ({ MessageBox: 'MessageBox' }))
vi.mock('../../../components/pr-sidebar/MermaidDiagram', () => ({
MermaidDiagram: 'MermaidDiagram'
}))
vi.mock('../../../components/MobileSourceCopyButton', () => ({
MobileSourceCopyButton: 'MobileSourceCopyButton'
}))
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
const flatten = (node: ReactTestInstance | string): string =>
typeof node === 'string' ? node : node.children.map(flatten).join('')
const flattenStyle = (style: unknown): Record<string, unknown> =>
Array.isArray(style)
? Object.assign({}, ...style.map(flattenStyle))
: style && typeof style === 'object'
? Object.fromEntries(Object.entries(style))
: {}
// A terminal-backed question reaches the phone as plain agent text, which names files like any chat text.
it('opens a file named in a question card through the chat', () => {
const openFile = vi.fn()
act(() => {
renderer = create(
createElement(
MobileNativeChatOpenFileContext,
{ value: openFile },
createElement(MobileNativeChatQuestion, {
question: {
question: 'Should I keep the **retry** in src/app.ts?',
options: ['Yes', 'No'],
multiSelect: false,
optionTokens: [null, null]
},
onAnswer: async () => true
})
)
)
})
const link = renderer!.root.find(
(node) =>
String(node.type) === 'Text' &&
typeof node.props.onPress === 'function' &&
flatten(node) === 'src/app.ts'
)
act(() => link.props.onPress())
expect(openFile).toHaveBeenCalledExactlyOnceWith('src/app.ts')
// The title is already strong, so the agent's bold must still read heavier than it.
const boldWeights = renderer!.root
.findAll((node) => String(node.type) === 'Text' && flatten(node) === 'retry')
.map((node) => flattenStyle(node.props.style).fontWeight)
expect(boldWeights).toContain('700')
})
@@ -230,12 +230,6 @@ describe('current recovery publication and normal Resume', () => {
})
describe('saved independent hold through feed, controller, tray and normal header', () => {
const r = queuedDraft({
messageId: 'R',
position: 0,
state: 'waiting',
paused: true
})
const w1 = queuedDraft({ messageId: 'W1', position: 1 })
const q = queuedDraft({
messageId: 'Q',
@@ -311,86 +305,6 @@ describe('current recovery publication and normal Resume', () => {
}
)
it('retains the published barrier across a withheld catch-up tuple and bounds/old-host/no-pause cases', async () => {
showTray = true
await mountSession(CAPABLE, snapshotEvent({ queuedMessages: [r, w1, q, w2] }))
act(() => listener?.(batchEvent([r, w1, q, w2], [], { reason: 'stopped' })))
expect(header()).toHaveLength(1)
vi.useFakeTimers()
act(() => {
listener?.(batchEvent(undefined, [acceptedSubmission('handoff-W1', 'W1')]))
vi.advanceTimersByTime(STRUCTURED_AGENT_SESSION_CLIENT_COALESCE_MS)
})
expect(hook!.queued.cards.map((c) => c.messageId)).toEqual(['R', 'Q', 'W2'])
expect(hook!.queued.cards.at(-1)?.caption).toBe('Waiting — a message ahead needs attention')
expect(header()).toHaveLength(0)
act(() =>
listener?.(
batchEvent(
[r, w1, queuedDraft({ messageId: 'W0', position: 1.5 }), q, w2],
[acceptedSubmission('handoff-W1', 'W1')],
{ reason: 'stopped' }
)
)
)
expect(header()).toHaveLength(1)
for (const queuedMessages of [
[q, w2],
[r],
[],
[queuedDraft({ messageId: 'P', paused: true })],
[{ ...r, state: 'returned' as const, paused: undefined }, w2]
]) {
act(() => listener?.(batchEvent(queuedMessages, [], { reason: 'stopped' })))
expect(header()).toHaveLength(0)
}
act(() =>
listener?.(
batchEvent([w1], [acceptedSubmission('handoff-W1', 'W1')], { reason: 'stopped' })
)
)
expect(hook!.queued.cards).toEqual([])
expect(header()).toHaveLength(0)
act(() => listener?.(snapshotEvent({ queuedMessages: [w1, { ...r, position: 2 }, w2] })))
expect(hook!.queued.cards.map((c) => c.caption)).toEqual([null, 'Paused', null])
expect(header()).toHaveLength(0)
})
it.each([100, 1000])(
'bounds actual publication/feed/controller join work at N=%i',
async (n) => {
await mountSession({ ...CAPABLE, queuedMessageReorder: true })
vi.useFakeTimers()
let reads = 0
const messages = Array.from({ length: n }, (_, i) => {
const message = queuedDraft({ messageId: `W${i}`, position: i })
return {
...message,
get messageId() {
reads++
return message.messageId
}
}
})
act(() => listener?.(batchEvent(messages, [], { reason: 'stopped' })))
expect(hook!.queued.cards).toHaveLength(n)
expect(hook!.queued.pause).toEqual({ reason: 'stopped' })
expect(reads).toBeGreaterThanOrEqual(n)
expect(reads).toBeLessThanOrEqual(20 * n)
const before = reads
act(() => {
listener?.(
batchEvent(undefined, [acceptedSubmission('handoff-W0', 'W0')], { reason: 'stopped' })
)
vi.advanceTimersByTime(STRUCTURED_AGENT_SESSION_CLIENT_COALESCE_MS)
})
expect(hook!.queued.cards).toHaveLength(n - 1)
expect(hook!.queued.cards.some((card) => card.messageId === 'W0')).toBe(false)
expect(reads - before).toBeGreaterThanOrEqual(n)
expect(reads - before).toBeLessThanOrEqual(20 * n)
}
)
it('intersects a pending raw preview with fresh visibility and facts, retaining hidden-anchor order and refusal rollback', async () => {
await mountSession(
{ ...CAPABLE, queuedMessageReorder: true },
-505
View File
@@ -1,505 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
const { listEnvironmentsMock, resolveEnvironmentMock, getDefaultUserDataPathMock } = vi.hoisted(
() => ({
listEnvironmentsMock: vi.fn(),
resolveEnvironmentMock: vi.fn(),
getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data')
})
)
vi.mock('./runtime/environments', () => ({
addEnvironmentFromPairingCode: vi.fn(),
removeEnvironment: vi.fn(),
resolveEnvironment: resolveEnvironmentMock
}))
vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: listEnvironmentsMock
}))
vi.mock('./runtime-client', () => ({
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
import {
resolveEnvironmentSelectorForStore,
hostFilterMatchesHostId,
parseHostFlag,
resolveHostFlagEnvironmentId,
resolveHostFlagTarget
} from './execution-host-flag'
import { parseExecutionHostId } from '../shared/execution-host'
import type { RuntimeClient } from './runtime-client'
const listSshTargetsMock = vi.fn(async () => [] as { id: string; label: string }[])
const NO_SELECTION = {
listSshTargets: listSshTargetsMock,
verifySshTargets: listSshTargetsMock,
pairingCode: null,
environmentSelector: null
}
function flags(entries: Record<string, string | boolean>): Map<string, string | boolean> {
return new Map(Object.entries(entries))
}
function environment(id: string, name = id) {
return { id, name }
}
describe('parseHostFlag', () => {
it('returns undefined when --host is absent', () => {
expect(parseHostFlag(flags({}))).toBeUndefined()
})
it('rejects a --host flag with no value', () => {
expect(() => parseHostFlag(flags({ host: true }))).toThrow('Missing value for --host')
})
it.each(['runtime:', 'ssh:', 'ssh:a|b', ' '])('rejects the unparseable host id %s', (value) => {
expect(() => parseHostFlag(flags({ host: value }))).toThrow(`Invalid --host value: ${value}`)
})
it('parses the three supported host kinds', () => {
expect(parseHostFlag(flags({ host: 'local' }))?.kind).toBe('local')
expect(parseHostFlag(flags({ host: 'ssh:box-1' }))?.kind).toBe('ssh')
expect(parseHostFlag(flags({ host: 'runtime:env-1' }))).toEqual({
kind: 'runtime',
id: 'runtime:env-1',
environmentId: 'env-1'
})
})
it('carries an unprefixed host name through as an alias', () => {
expect(parseHostFlag(flags({ host: 'trader-local' }))).toEqual({
kind: 'alias',
alias: 'trader-local'
})
expect(parseHostFlag(flags({ host: ' trader-local ' }))).toEqual({
kind: 'alias',
alias: 'trader-local'
})
})
})
describe('resolveHostFlagEnvironmentId', () => {
it('keeps the current connection for local and ssh hosts', async () => {
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'local' }), NO_SELECTION)
).resolves.toBe(null)
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'ssh:box-1' }), NO_SELECTION)
).resolves.toBe(null)
expect(listEnvironmentsMock).not.toHaveBeenCalled()
})
it('routes a paired runtime host to that environment', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env-1' }), NO_SELECTION)
).resolves.toBe('env-1')
})
it('rejects a runtime host id that no paired environment owns', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env-missing' }), NO_SELECTION)
).rejects.toThrow('no paired Orca server is named or has id env-missing')
})
it('accepts the environment name as well as its id', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:gpu' }), NO_SELECTION)
).resolves.toBe('env-1')
})
it('decodes percent-encoded environment ids', async () => {
listEnvironmentsMock.mockReturnValue([environment('env one')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env%20one' }), NO_SELECTION)
).resolves.toBe('env one')
})
it('refuses a runtime host alongside --pairing-code', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env-1' }), {
listSshTargets: listSshTargetsMock,
verifySshTargets: listSshTargetsMock,
pairingCode: 'orca://pair?x',
environmentSelector: null
})
).rejects.toThrow('not both')
})
it('refuses a runtime host that disagrees with --environment', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1')])
resolveEnvironmentMock.mockReturnValue(environment('env-2'))
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env-1' }), {
listSshTargets: listSshTargetsMock,
verifySshTargets: listSshTargetsMock,
pairingCode: null,
environmentSelector: { value: 'other', label: '--environment' }
})
).rejects.toThrow('name different Orca servers')
})
it('names the ambient variable when ORCA_ENVIRONMENT is the conflicting selector', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1')])
resolveEnvironmentMock.mockReturnValue(environment('env-2'))
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env-1' }), {
listSshTargets: listSshTargetsMock,
verifySshTargets: listSshTargetsMock,
pairingCode: null,
environmentSelector: { value: 'staging', label: 'ORCA_ENVIRONMENT' }
})
).rejects.toThrow('ORCA_ENVIRONMENT staging name different Orca servers')
})
it('hands an agent the known environment ids to retry with', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:missing' }), NO_SELECTION)
).rejects.toMatchObject({
code: 'invalid_argument',
data: { knownEnvironments: [{ id: 'env-1', name: 'gpu' }] }
})
})
it('accepts ORCA_ENVIRONMENT naming the runtime host in another case', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'Build')])
resolveEnvironmentMock.mockImplementation(() => {
throw new Error('Unknown environment: build')
})
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env-1' }), {
listSshTargets: listSshTargetsMock,
verifySshTargets: listSshTargetsMock,
pairingCode: null,
environmentSelector: { value: 'build', label: 'ORCA_ENVIRONMENT' }
})
).resolves.toBe('env-1')
resolveEnvironmentMock.mockReset()
})
it('accepts --environment naming the same server as the runtime host', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
resolveEnvironmentMock.mockReturnValue(environment('env-1', 'gpu'))
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env-1' }), {
listSshTargets: listSshTargetsMock,
verifySshTargets: listSshTargetsMock,
pairingCode: null,
environmentSelector: { value: 'gpu', label: '--environment' }
})
).resolves.toBe('env-1')
})
})
describe('unprefixed --host aliases', () => {
function clientWithTargets(targets: { id: string; label: string }[]): RuntimeClient {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SSH target resolution reads only client.call.
return {
call: vi.fn(async () => ({ result: { targets } }))
} as unknown as RuntimeClient
}
it('routes an alias that names a paired server to that environment', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
listSshTargetsMock.mockResolvedValue([])
await expect(resolveHostFlagEnvironmentId(flags({ host: 'gpu' }), NO_SELECTION)).resolves.toBe(
'env-1'
)
})
it('leaves an alias that names no paired server to the SSH axis', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'trader-local' }), NO_SELECTION)
).resolves.toBe(null)
})
it('resolves an alias to the SSH target that carries that label', async () => {
listEnvironmentsMock.mockReturnValue([])
const client = clientWithTargets([{ id: 'ssh-1783599077486-fyasux', label: 'trader-local' }])
await expect(resolveHostFlagTarget(flags({ host: 'trader-local' }), client)).resolves.toEqual({
kind: 'ssh',
id: 'ssh:ssh-1783599077486-fyasux',
targetId: 'ssh-1783599077486-fyasux'
})
})
it('names the alias the caller typed rather than an ssh: spelling they did not use', async () => {
listEnvironmentsMock.mockReturnValue([])
await expect(
resolveHostFlagTarget(flags({ host: 'trader-local' }), clientWithTargets([]))
).rejects.toThrow('Unknown host in --host trader-local')
})
it('refuses an alias that names a machine on both axes', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'awin')])
listSshTargetsMock.mockResolvedValue([{ id: 'ssh-1-a', label: 'awin' }])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'awin' }), NO_SELECTION)
).rejects.toMatchObject({
code: 'invalid_argument',
data: {
nextSteps: expect.arrayContaining([
expect.stringContaining('--host runtime:env-1'),
expect.stringContaining('--host ssh:ssh-1-a')
])
}
})
})
it('refuses an alias naming a server and two SSH targets sharing a label', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'awin')])
listSshTargetsMock.mockResolvedValue([
{ id: 'ssh-1-a', label: 'awin' },
{ id: 'ssh-2-b', label: 'awin' }
])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'awin' }), NO_SELECTION)
).rejects.toMatchObject({
code: 'invalid_argument',
data: {
nextSteps: expect.arrayContaining([
expect.stringContaining('--host runtime:env-1'),
expect.stringContaining('--host ssh:ssh-1-a'),
expect.stringContaining('--host ssh:ssh-2-b')
])
}
})
})
it('refuses an alias two paired servers answer to', async () => {
listEnvironmentsMock.mockReturnValue([
environment('env-1', 'awin'),
environment('env-2', 'awin')
])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'awin' }), NO_SELECTION)
).rejects.toThrow('Ambiguous Orca server in --host awin')
})
it('refuses to route an alias to a paired server when SSH targets cannot be read', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'awin')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'awin' }), {
...NO_SELECTION,
verifySshTargets: async () => {
throw new Error('runtime unreachable')
}
})
).rejects.toMatchObject({
message: expect.stringContaining('Cannot verify --host awin'),
data: { nextSteps: [expect.stringContaining('--host runtime:env-1')] }
})
})
it('resolves the local row name to --host local', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'This Machine' }), NO_SELECTION)
).resolves.toBe(null)
await expect(
resolveHostFlagTarget(flags({ host: 'this machine' }), clientWithTargets([]))
).resolves.toEqual({ kind: 'local', id: 'local' })
})
it('refuses the local row name when an SSH target carries it too', async () => {
listEnvironmentsMock.mockReturnValue([])
await expect(
resolveHostFlagTarget(
flags({ host: 'this machine' }),
clientWithTargets([{ id: 'ssh-1-a', label: 'this machine' }])
)
).rejects.toMatchObject({
message: expect.stringContaining('Ambiguous --host this machine'),
data: {
nextSteps: expect.arrayContaining([
'Use --host local for this machine.',
expect.stringContaining('--host ssh:ssh-1-a')
])
}
})
})
it('refuses the local row name when a paired server carries it too', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'this machine')])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'this machine' }), NO_SELECTION)
).rejects.toThrow('Ambiguous --host this machine')
})
it('resolves an SSH target label that contains spaces', async () => {
listEnvironmentsMock.mockReturnValue([])
const client = clientWithTargets([{ id: 'ssh-9', label: 'Build Box 2' }])
await expect(resolveHostFlagTarget(flags({ host: 'build box 2' }), client)).resolves.toEqual({
kind: 'ssh',
id: 'ssh:ssh-9',
targetId: 'ssh-9'
})
})
// cmd.exe passes wrapping single quotes through literally.
it('ignores one pair of wrapping quotes around a host name', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'gpu')])
listSshTargetsMock.mockResolvedValue([])
await expect(
resolveHostFlagEnvironmentId(flags({ host: "'gpu'" }), NO_SELECTION)
).resolves.toBe('env-1')
expect(parseHostFlag(flags({ host: '"local"' }))).toEqual({ kind: 'local', id: 'local' })
})
it('leaves an alias to the routed server SSH targets when --environment picks the server', async () => {
listEnvironmentsMock.mockReturnValue([
environment('env-1', 'openclaw'),
environment('env-2', 'omarchy')
])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'omarchy' }), {
...NO_SELECTION,
environmentSelector: { value: 'openclaw', label: '--environment' }
})
).resolves.toBe(null)
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'openclaw' }), {
...NO_SELECTION,
environmentSelector: { value: 'openclaw', label: '--environment' }
})
).resolves.toBe(null)
})
})
describe('hostFilterMatchesHostId', () => {
const runtimeHost = parseExecutionHostId('runtime:env-1')!
const localHost = parseExecutionHostId('local')!
const sshHost = parseExecutionHostId('ssh:box-1')!
it('matches the identical host id', () => {
expect(hostFilterMatchesHostId(runtimeHost, 'runtime:env-1')).toBe(true)
expect(hostFilterMatchesHostId(localHost, 'local')).toBe(true)
expect(hostFilterMatchesHostId(sshHost, 'ssh:box-1')).toBe(true)
})
it('treats the routed runtime own local rows as that runtime', () => {
expect(hostFilterMatchesHostId(runtimeHost, 'local')).toBe(true)
})
it('does not widen local or ssh filters', () => {
expect(hostFilterMatchesHostId(localHost, 'runtime:env-1')).toBe(false)
expect(hostFilterMatchesHostId(sshHost, 'local')).toBe(false)
})
it('does not match a different runtime host', () => {
expect(hostFilterMatchesHostId(runtimeHost, 'runtime:env-2')).toBe(false)
expect(hostFilterMatchesHostId(runtimeHost, null)).toBe(false)
})
})
describe('ambiguous environment names', () => {
it('refuses --host runtime:<name> when two servers share that name', async () => {
listEnvironmentsMock.mockReturnValue([
environment('env-1', 'awin'),
environment('env-2', 'awin')
])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:awin' }), NO_SELECTION)
).rejects.toThrow('2 paired servers are named awin')
})
it('refuses --environment <name> when two servers share that name', async () => {
listEnvironmentsMock.mockReturnValue([
environment('env-1', 'awin'),
environment('env-2', 'awin')
])
await expect(resolveEnvironmentSelectorForStore('awin', listSshTargetsMock)).rejects.toThrow(
'2 paired servers are named awin'
)
})
it('still routes an exact id past a colliding name', async () => {
listEnvironmentsMock.mockReturnValue([
environment('env-1', 'awin'),
environment('env-2', 'awin')
])
await expect(
resolveHostFlagEnvironmentId(flags({ host: 'runtime:env-2' }), NO_SELECTION)
).resolves.toBe('env-2')
})
})
describe('resolveEnvironmentSelectorForStore', () => {
it('accepts a paired server by name or id', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'awin')])
listSshTargetsMock.mockClear()
await expect(resolveEnvironmentSelectorForStore('awin', listSshTargetsMock)).resolves.toBe(
'awin'
)
await expect(resolveEnvironmentSelectorForStore('env-1', listSshTargetsMock)).resolves.toBe(
'env-1'
)
expect(listSshTargetsMock).not.toHaveBeenCalled()
})
// The store matches names exactly; canonicalize loose matches to IDs.
it('hands back the id for a name typed in another case or quoted', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'Build')])
await expect(resolveEnvironmentSelectorForStore('build', listSshTargetsMock)).resolves.toBe(
'env-1'
)
await expect(resolveEnvironmentSelectorForStore('"BUILD"', listSshTargetsMock)).resolves.toBe(
'env-1'
)
})
it('names the SSH target when the selector is one', async () => {
listEnvironmentsMock.mockReturnValue([environment('env-1', 'awin')])
listSshTargetsMock.mockResolvedValue([{ id: 'ssh-1-a', label: 'openclaw' }])
await expect(
resolveEnvironmentSelectorForStore('openclaw', listSshTargetsMock)
).rejects.toMatchObject({
code: 'invalid_argument',
data: {
nextSteps: expect.arrayContaining([expect.stringContaining('--host ssh:ssh-1-a')])
}
})
})
it('still points at host list when the name is on neither axis', async () => {
listEnvironmentsMock.mockReturnValue([])
listSshTargetsMock.mockResolvedValue([])
await expect(resolveEnvironmentSelectorForStore('nowhere', listSshTargetsMock)).rejects.toThrow(
'no paired Orca server is named or has id nowhere'
)
})
})
+2 -630
View File
@@ -1,14 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient, RuntimeClientError } from '../runtime-client'
import { RuntimeClient } from '../runtime-client'
import type { CliStatusResult } from '../../shared/runtime-types'
import '../../shared/protocol-version'
import {
TERMINAL_CREATE_SHELL_SELECTION_RUNTIME_CAPABILITY,
TERMINAL_PROMPT_DELIVERY_RUNTIME_CAPABILITY
} from '../../shared/terminal/runtime-policy/terminal-runtime-capabilities'
import { parseArgs } from '../args'
import { printHelp } from '../help'
import { COMMAND_SPECS } from '../specs'
import { TERMINAL_PROMPT_DELIVERY_RUNTIME_CAPABILITY } from '../../shared/terminal/runtime-policy/terminal-runtime-capabilities'
import { TERMINAL_HANDLERS } from './terminal'
const ORIGINAL_EXIT_CODE = process.exitCode
@@ -40,31 +34,6 @@ describe('terminal close CLI', () => {
process.exitCode = ORIGINAL_EXIT_CODE
})
it('keeps the default close RPC unchanged', async () => {
process.exitCode = undefined
const call = vi.fn().mockResolvedValue({
id: 'req-close',
ok: true,
result: { close: { handle: 'term-1', tabId: 'tab-1', ptyKilled: true } },
_meta: { runtimeId: 'runtime-1' }
})
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal close']({
flags: new Map([['terminal', 'term-1']]),
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
expect(call).toHaveBeenCalledWith('terminal.close', { terminal: 'term-1' })
expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({
ok: true,
result: { close: { ptyKilled: true } }
})
expect(process.exitCode).toBeUndefined()
})
it.each([
[
'its SSH provider is no longer registered',
@@ -117,74 +86,6 @@ describe('terminal close CLI', () => {
}
)
it('reports a live PTY stop as a failing human outcome', async () => {
process.exitCode = undefined
const close = {
handle: 'term-live',
tabId: 'tab-1',
ptyKilled: false,
ptyStopVerdict: 'live' as const
}
const call = vi.fn().mockResolvedValue({ result: { close } })
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal close']({
flags: new Map([['terminal', close.handle]]),
client: terminalClient(call),
cwd: '/tmp/worktree',
json: false
})
expect(log).toHaveBeenCalledWith(expect.stringContaining('The PTY is live.'))
expect(process.exitCode).toBe(1)
})
it('routes --tab to the durable whole-tab RPC', async () => {
process.exitCode = undefined
const parsed = parseArgs(['terminal', 'close', '--terminal', 'term-1', '--tab'])
const call = vi.fn().mockResolvedValue({
result: {
close: {
handle: 'term-1',
tabId: 'tab-1',
closeMode: 'tab',
ptyKilled: false
}
}
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal close']({
flags: parsed.flags,
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
expect(parsed.flags.get('tab')).toBe(true)
expect(call).toHaveBeenCalledWith('terminal.closeTab', { terminal: 'term-1' })
expect(process.exitCode).toBeUndefined()
})
it('routes --worktree --all to authoritative durable bulk close', async () => {
const parsed = parseArgs(['terminal', 'close', '--worktree', 'id:repo::/worktree', '--all'])
const call = vi.fn().mockResolvedValue({
result: { closed: 2, stopped: 3, retiredSurfaces: true }
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal close']({
flags: parsed.flags,
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
expect(call).toHaveBeenCalledWith('terminal.closeAll', {
worktree: 'id:repo::/worktree'
})
})
it('fails JSON when bulk close cannot verify every PTY stopped', async () => {
process.exitCode = undefined
const call = vi.fn().mockResolvedValue({
@@ -217,322 +118,14 @@ describe('terminal close CLI', () => {
})
expect(process.exitCode).toBe(1)
})
it.each([
[new Map<string, string | true>([['worktree', 'active']]), 'requires --all'],
[
new Map<string, string | true>([
['worktree', 'active'],
['all', true],
['terminal', 'term-1']
]),
'cannot be combined'
],
[new Map<string, string | true>([['all', true]]), 'Missing required --worktree']
])('rejects ambiguous bulk-close flags', async (flags, message) => {
const call = vi.fn()
await expect(
TERMINAL_HANDLERS['terminal close']({
flags,
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
).rejects.toThrow(message)
expect(call).not.toHaveBeenCalled()
})
it('fails safely before mutation when the host predates bulk close', async () => {
const call = vi
.fn()
.mockRejectedValue(
new RuntimeClientError('method_not_found', 'Unknown method: terminal.closeAll')
)
await expect(
TERMINAL_HANDLERS['terminal close']({
flags: new Map<string, string | true>([
['worktree', 'id:repo::/worktree'],
['all', true]
]),
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
).rejects.toMatchObject({ code: 'incompatible_runtime' })
expect(call).toHaveBeenCalledExactlyOnceWith('terminal.closeAll', {
worktree: 'id:repo::/worktree'
})
})
it('documents that --tab waits for durable persistence', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
printHelp(COMMAND_SPECS, ['terminal', 'close'])
const help = String(log.mock.calls[0]?.[0])
expect(help).toContain('--worktree <selector> --all')
expect(help).toContain('durable persistence')
})
it.each(['send', 'read', 'wait', 'create'])(
'describes the server-selection flags in terminal %s help',
(verb) => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
printHelp(COMMAND_SPECS, ['terminal', verb])
const help = String(log.mock.calls[0]?.[0])
expect(help).toMatch(/--environment <selector> .*paired Orca server/)
expect(help).toMatch(/--pairing-code <code> .*orca:\/\/pair/)
log.mockRestore()
}
)
it('hides legacy stop from terminal command discovery', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
printHelp(COMMAND_SPECS, ['terminal'])
const help = String(log.mock.calls[0]?.[0])
expect(help).toContain('close')
expect(help).not.toContain('stop')
})
it('keeps root help aligned with the canonical close command', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
printHelp(COMMAND_SPECS)
const help = String(log.mock.calls[0]?.[0])
expect(help).toContain(
'terminal close Close one terminal, its whole tab with --tab, or all in a worktree'
)
expect(help).not.toContain('terminal stop')
})
})
describe('terminal send CLI', () => {
const promptClient = (call: RuntimeClient['call'], supported: boolean) =>
terminalClient(call, {
state: 'ready',
reachable: true,
runtimeId: 'runtime-current',
capabilities: supported ? [TERMINAL_PROMPT_DELIVERY_RUNTIME_CAPABILITY] : []
})
afterEach(() => {
vi.restoreAllMocks()
process.exitCode = ORIGINAL_EXIT_CODE
})
it('marks combined text and Enter as an agent prompt candidate', async () => {
const call = vi.fn().mockResolvedValue({
result: {
send: {
handle: 'term-1',
accepted: true,
bytesWritten: 7,
prompt: {
requestId: '11111111-1111-4111-8111-111111111111',
stages: ['input_accepted'],
provider: 'codex',
observation: 'supported',
processIncarnation: 'inc-1',
generation: 1,
baselineWorkingSequence: 0
}
}
}
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'review'],
['enter', true]
]),
client: promptClient(call, true),
cwd: '/tmp/worktree',
json: true
})
expect(call).toHaveBeenCalledWith(
'terminal.send',
{
terminal: 'term-1',
text: 'review',
enter: true,
interrupt: false,
agentPrompt: true,
client: { id: 'orca-cli', type: 'desktop' }
},
{ terminalPromptPreflight: { runtimeId: 'runtime-current' } }
)
})
it('carries the swallowed-Enter warning into the --json receipt', async () => {
const call = vi.fn().mockResolvedValue({
result: {
send: {
handle: 'term-1',
accepted: true,
bytesWritten: 7,
prompt: {
requestId: 'prompt-swallowed',
stages: ['input_accepted'],
provider: 'claude',
observation: 'supported',
processIncarnation: 'inc-1',
generation: 1,
baselineWorkingSequence: 0
}
}
}
})
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'review'],
['enter', true]
]),
client: promptClient(call, true),
cwd: '/tmp/worktree',
json: true
})
expect(JSON.parse(String(log.mock.calls[0]?.[0])).result.warnings).toEqual([
expect.stringContaining('no turn start was observed')
])
})
it("reports an older host's lease refusal as a plain refused send", async () => {
const call = vi.fn().mockResolvedValue({
result: {
send: {
handle: 'term-1',
accepted: false,
bytesWritten: 0,
agentSessionRefusal: {
code: 'agent_session_conflict',
sessionId: 'session-1',
ownerRuntimeKind: 'native',
handoffStage: null,
ownerPid: 4242,
runtimeFence: 7
}
}
}
})
vi.spyOn(console, 'log').mockImplementation(() => {})
process.exitCode = undefined
const client = promptClient(call, true)
await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'review'],
['enter', true]
]),
client,
cwd: '/tmp/worktree',
json: false
})
expect(client.getCliStatus).toHaveBeenCalledOnce()
expect(console.log).toHaveBeenCalledWith('Input refused by term-1.')
expect(process.exitCode).toBe(1)
})
it('keeps text-only and bare Enter sends as direct terminal input', async () => {
const call = vi.fn().mockResolvedValue({
result: { send: { handle: 'term-1', accepted: true, bytesWritten: 1 } }
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'x']
]),
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['enter', true]
]),
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
expect(call).toHaveBeenNthCalledWith(1, 'terminal.send', {
terminal: 'term-1',
text: 'x',
enter: false,
interrupt: false,
client: { id: 'orca-cli', type: 'desktop' }
})
expect(call).toHaveBeenNthCalledWith(2, 'terminal.send', {
terminal: 'term-1',
text: undefined,
enter: true,
interrupt: false,
client: { id: 'orca-cli', type: 'desktop' }
})
})
it('passes retry identity and observation wait only for agent prompts', async () => {
const call = vi.fn().mockResolvedValue({
result: {
send: {
handle: 'term-1',
accepted: true,
bytesWritten: 8,
prompt: {
requestId: '11111111-1111-4111-8111-111111111111',
stages: ['input_accepted'],
provider: 'codex',
observation: 'supported',
processIncarnation: 'inc-1',
generation: 1,
baselineWorkingSequence: 1
}
}
}
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'continue'],
['enter', true],
['retry-request', '11111111-1111-4111-8111-111111111111'],
['wait-submit', '3']
]),
client: promptClient(call, true),
cwd: '/tmp/worktree',
json: true
})
expect(call).toHaveBeenCalledWith(
'terminal.send',
expect.objectContaining({ agentPrompt: true, waitSubmitMs: 3_000 }),
{
terminalPromptPreflight: { runtimeId: 'runtime-current' },
orchestrationRequestId: '11111111-1111-4111-8111-111111111111',
timeoutMs: 13_000
}
)
})
it('fails closed when the host downgrades after the prompt capability preflight', async () => {
const response = {
result: { send: { handle: 'term-1', accepted: true, bytesWritten: 8 } },
@@ -582,225 +175,4 @@ describe('terminal send CLI', () => {
})
expect(log).not.toHaveBeenCalled()
})
it('labels an old-host response as non-idempotent without claiming submission', async () => {
const call = vi.fn().mockResolvedValue({
result: { send: { handle: 'term-1', accepted: true, bytesWritten: 7 } }
})
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'review'],
['enter', true]
]),
client: promptClient(call, false),
cwd: '/tmp/worktree',
json: true
})
expect(call).toHaveBeenCalledWith(
'terminal.send',
expect.objectContaining({ agentPrompt: true }),
{ legacyTerminalPrompt: true }
)
expect(JSON.parse(String(log.mock.calls[0]?.[0])).result.send.prompt).toEqual({
requestId: 'unsupported-old-host',
stages: ['input_accepted'],
provider: 'old-host',
observation: 'unsupported',
processIncarnation: 'unknown',
generation: 0,
baselineWorkingSequence: 0
})
})
it('reports an old-host refusal with its permission reason', async () => {
const call = vi.fn().mockResolvedValue({
result: {
send: {
handle: 'term-1',
accepted: false,
bytesWritten: 0,
refusedReason: 'permission'
}
}
})
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'review'],
['enter', true]
]),
client: promptClient(call, false),
cwd: '/tmp/worktree',
json: false
})
expect(String(log.mock.calls[0]?.[0])).toBe('Input refused by term-1: permission.')
})
it('refuses old-host retry before sending any input', async () => {
const call = vi.fn()
vi.spyOn(console, 'log').mockImplementation(() => {})
const error = await TERMINAL_HANDLERS['terminal send']({
flags: new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'review'],
['enter', true],
['retry-request', '11111111-1111-4111-8111-111111111111']
]),
client: promptClient(call, false),
cwd: '/tmp/worktree',
json: true
})
.then(() => undefined)
.catch((caught: unknown) => caught)
expect(error).toMatchObject({
code: 'incompatible_runtime',
message: expect.stringContaining(
'updating the host cannot make this specific retry idempotent'
)
})
expect(error).not.toMatchObject({ message: expect.stringContaining('omit --retry-request') })
expect(call).not.toHaveBeenCalled()
})
it('preserves retry identity after a pre-write host failure', async () => {
const call = vi
.fn()
.mockRejectedValueOnce(new RuntimeClientError('internal_error', 'terminal_not_writable'))
.mockResolvedValueOnce({
result: {
send: {
handle: 'term-1',
accepted: true,
bytesWritten: 13,
prompt: {
requestId: '22222222-2222-4222-8222-222222222222',
stages: ['input_accepted'],
provider: 'codex',
observation: 'supported',
processIncarnation: 'inc-1',
generation: 1,
baselineWorkingSequence: 0
}
}
}
})
const client = promptClient(call, true)
const flags = new Map<string, string | true>([
['terminal', 'term-1'],
['text', 'retry safely'],
['enter', true],
['retry-request', '22222222-2222-4222-8222-222222222222']
])
vi.spyOn(console, 'log').mockImplementation(() => {})
await expect(
TERMINAL_HANDLERS['terminal send']({ flags, client, cwd: '/tmp/worktree', json: true })
).rejects.toMatchObject({ message: 'terminal_not_writable' })
await TERMINAL_HANDLERS['terminal send']({
flags,
client,
cwd: '/tmp/worktree',
json: true
})
expect(call).toHaveBeenCalledTimes(2)
expect(call.mock.calls.map((args) => args[2])).toEqual([
{
terminalPromptPreflight: { runtimeId: 'runtime-current' },
orchestrationRequestId: '22222222-2222-4222-8222-222222222222'
},
{
terminalPromptPreflight: { runtimeId: 'runtime-current' },
orchestrationRequestId: '22222222-2222-4222-8222-222222222222'
}
])
})
})
describe('terminal create --shell', () => {
const WORKTREE = 'path:C:/src/app'
const shellClient = (
call: RuntimeClient['call'],
supported: boolean,
reachable = true
): RuntimeClient => {
return terminalClient(call, {
state: reachable ? 'ready' : 'not_running',
reachable,
runtimeId: reachable ? 'runtime-current' : null,
...(reachable
? { capabilities: supported ? [TERMINAL_CREATE_SHELL_SELECTION_RUNTIME_CAPABILITY] : [] }
: {})
})
}
afterEach(() => {
vi.restoreAllMocks()
process.exitCode = ORIGINAL_EXIT_CODE
})
function createTerminal(client: RuntimeClient, shell: string) {
return TERMINAL_HANDLERS['terminal create']({
flags: new Map([
['worktree', WORKTREE],
['shell', shell]
]),
client,
cwd: 'C:/src/app',
json: true
})
}
it('sends the shell selection alongside an empty startup command', async () => {
const call = vi.fn().mockResolvedValue({
result: { terminal: { handle: 'term_1', worktreeId: 'repo::C:/src/app', title: null } }
})
vi.spyOn(console, 'log').mockImplementation(() => {})
await createTerminal(shellClient(call, true), 'cmd.exe')
expect(call).toHaveBeenCalledWith(
'terminal.create',
expect.objectContaining({ shell: 'cmd.exe', command: undefined })
)
})
it('refuses a shell the host cannot spawn without making the round trip', async () => {
const call = vi.fn()
await expect(createTerminal(shellClient(call, true), 'nu.exe')).rejects.toThrow(
/--shell must be one of/
)
expect(call).not.toHaveBeenCalled()
})
// Older hosts ignore shell and report a successful create using their default shell.
it('refuses rather than creating a default-shell terminal on a host without the capability', async () => {
const call = vi.fn()
await expect(createTerminal(shellClient(call, false), 'cmd.exe')).rejects.toThrow(
/does not support --shell/
)
expect(call).not.toHaveBeenCalled()
})
// Missing capabilities on an unreachable runtime do not establish a version gap.
it('reports an unreachable host as unavailable rather than incompatible', async () => {
const call = vi.fn()
await expect(createTerminal(shellClient(call, false, false), 'cmd.exe')).rejects.toMatchObject({
code: 'runtime_unavailable'
})
expect(call).not.toHaveBeenCalled()
})
})
+3 -220
View File
@@ -45,9 +45,9 @@ vi.mock('child_process', async () => {
import { main } from './index'
import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client'
import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from './test-fixtures'
import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness'
import { agentLaunchFixture, agentLaunchHostFixture } from './agent-launch-test-fixtures'
import { queueFixtures } from './test-fixtures'
import { useWorktreeAwarenessEnvironment } from './index-test-harness'
import { agentLaunchHostFixture } from './agent-launch-test-fixtures'
const WORKTREE_ID = 'repo-1::/tmp/repo'
const ORIGINAL_EXIT_CODE = process.exitCode
@@ -81,89 +81,6 @@ describe('orca cli agent launch', () => {
spawnMock
})
it('starts an agent in the current worktree through agent.launch', async () => {
queueFixtures(
callMock,
okFixture('req_folders', { folderWorkspaces: [] }),
worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]),
agentLaunchHostFixture(),
agentLaunchFixture(WORKTREE_ID)
)
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
[
'agent',
'launch',
'--agent',
'codex',
'--model',
'gpt-5.5',
'--effort',
'high',
'--prompt',
'Write the design doc',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenNthCalledWith(4, 'agent.launchReplay', {
target: { kind: 'existing', worktree: `id:${WORKTREE_ID}` },
presentation: 'background',
agent: 'codex',
prompt: { text: 'Write the design doc', delivery: 'submit' },
sessionOptions: { model: 'gpt-5.5', effort: 'high' },
launchSource: 'cli',
operationId: expect.any(String)
})
expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).result.receipt.reason).toBe('user_default')
})
it('switches to the new tab only with --focus', async () => {
queueFixtures(callMock, agentLaunchHostFixture(), agentLaunchFixture(WORKTREE_ID))
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
['agent', 'launch', '--agent', 'claude', '--worktree', `id:${WORKTREE_ID}`, '--focus'],
'/tmp/repo'
)
expect(callMock).toHaveBeenCalledWith('agent.launchReplay', {
target: { kind: 'existing', worktree: `id:${WORKTREE_ID}` },
presentation: 'focused',
agent: 'claude',
launchSource: 'cli',
operationId: expect.any(String)
})
})
it('honors the paired execution host for agent launch', async () => {
pairRuntimeEnvironment(listEnvironmentsMock, 'server-1')
queueFixtures(callMock, agentLaunchHostFixture(), agentLaunchFixture('folder:server-folder'))
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
[
'agent',
'launch',
'--agent',
'codex',
'--environment',
'server-1',
'--worktree',
'id:folder:server-folder',
'--json'
],
'/tmp/repo'
)
expect(runtimeClientConstructorMock).toHaveBeenCalledWith(undefined, 'server-1')
expect(callMock).toHaveBeenCalledWith(
'agent.launchReplay',
expect.objectContaining({ target: { kind: 'existing', worktree: 'id:folder:server-folder' } })
)
expect(callMock).not.toHaveBeenCalledWith('folderWorkspace.list')
})
it('returns an exact recovery command and removes blind retry advice after a lost reply', async () => {
queueFixtures(callMock, agentLaunchHostFixture())
callMock.mockRejectedValueOnce(
@@ -200,27 +117,6 @@ describe('orca cli agent launch', () => {
])
})
it.each([['--retry-launch'], ['--retry-launch', ' ']])(
'rejects an invalid retry identity before launching: %j',
async (...retryArgs) => {
const output = await runRefused([
'agent',
'launch',
'--agent',
'codex',
'--worktree',
`id:${WORKTREE_ID}`,
...retryArgs,
'--json'
])
expect(JSON.parse(output).error).toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('--retry-launch')
})
expect(callMock).not.toHaveBeenCalled()
}
)
it('keeps recovery identity when an older replacement host refuses a replay method', async () => {
const operationId = `${Date.now()}-${'c'.repeat(32)}`
queueFixtures(callMock, agentLaunchHostFixture())
@@ -251,117 +147,4 @@ describe('orca cli agent launch', () => {
['agent.launchReplay', expect.objectContaining({ operationId })]
])
})
it('uses the caller folder identity after validating its native host and enclosing path', async () => {
process.env.ORCA_WORKSPACE_ID = 'folder:caller'
queueFixtures(
callMock,
okFixture('folders', {
folderWorkspaces: [
{ id: 'caller', folderPath: '/tmp/folder', projectGroupId: 'local' },
{ id: 'nested', folderPath: '/tmp/folder/src', projectGroupId: 'local' },
{ id: 'remote', folderPath: '/tmp/folder', projectGroupId: 'ssh' }
]
}),
okFixture('groups', { groups: [{ id: 'local' }, { id: 'ssh', connectionId: 'ssh-1' }] }),
okFixture('repos', { repos: [] }),
agentLaunchHostFixture(),
agentLaunchFixture('folder:caller')
)
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(['agent', 'launch', '--agent', 'codex', '--json'], '/tmp/folder/src/nested')
expect(callMock).toHaveBeenCalledWith(
'agent.launchReplay',
expect.objectContaining({ target: { kind: 'existing', worktree: 'id:folder:caller' } })
)
expect(callMock).not.toHaveBeenCalledWith('worktree.list', expect.anything())
})
it('ignores an inherited remote folder identity and uses the local Git fallback', async () => {
process.env.ORCA_WORKSPACE_ID = 'folder:remote'
queueFixtures(
callMock,
okFixture('folders', {
folderWorkspaces: [{ id: 'remote', folderPath: '/tmp/repo', projectGroupId: 'ssh' }]
}),
okFixture('groups', { groups: [{ id: 'ssh', connectionId: 'ssh-1' }] }),
okFixture('repos', { repos: [] }),
worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]),
agentLaunchHostFixture(),
agentLaunchFixture(WORKTREE_ID)
)
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(['agent', 'launch', '--agent', 'codex', '--json'], '/tmp/repo/src')
expect(callMock).toHaveBeenCalledWith(
'agent.launchReplay',
expect.objectContaining({ target: { kind: 'existing', worktree: `id:${WORKTREE_ID}` } })
)
})
it('refuses on a host older than agent.launch instead of opening a terminal', async () => {
queueFixtures(callMock, okFixture('req_status', { capabilities: [] }))
const output = await runRefused([
'agent',
'launch',
'--agent',
'codex',
'--worktree',
`id:${WORKTREE_ID}`,
'--json'
])
expect(JSON.parse(output).error).toMatchObject({
code: 'incompatible_runtime',
message: expect.stringContaining('cannot start agents from the CLI')
})
expect(launchCalls()).toEqual([])
})
it('refuses a model on a host older than agent.launch rather than dropping it', async () => {
queueFixtures(callMock, okFixture('req_status', { capabilities: [] }))
const output = await runRefused([
'worktree',
'create',
'--repo',
'id:repo-1',
'--name',
'design',
'--no-parent',
'--agent',
'codex',
'--model',
'gpt-5.5',
'--json'
])
expect(JSON.parse(output).error).toMatchObject({
code: 'incompatible_runtime',
message: expect.stringContaining('cannot start an agent on a chosen model or effort')
})
expect(launchCalls()).toEqual([])
})
it.each([
[['--agent', 'codex', '--effort', 'high'], '--effort requires --model'],
[['--model', 'gpt-5.5'], '--model requires --agent'],
[['--agent', 'codex', '--model', 'gpt-5.5', '--effort', 'turbo'], 'does not support effort'],
[['--surface', 'terminal'], '--surface requires --agent']
])('refuses %j before creating anything', async (flags, message) => {
const output = await runRefused([
'worktree',
'create',
'--repo',
'id:repo-1',
'--name',
'design',
'--no-parent',
...flags,
'--json'
])
expect(output).toContain(message)
expect(callMock).not.toHaveBeenCalled()
})
})
+1 -277
View File
@@ -46,7 +46,7 @@ vi.mock('child_process', async () => {
import { main } from './index'
import { okFixture, queueFixtures } from './test-fixtures'
import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness'
import { useWorktreeAwarenessEnvironment } from './index-test-harness'
const AUTOMATION_ID = '497bafa9-5a97-4f85-9e48-2b211b8f31fa'
const RUN_ID = 'd99b909f-c4a1-4b56-9979-abf57e94be11'
@@ -104,139 +104,6 @@ describe('automation run command output', () => {
vi.unstubAllEnvs()
})
it.each([
{ status: 'pending', acknowledgement: `Queued run ${RUN_ID} (pending).` },
{
status: 'dispatching',
acknowledgement: `Accepted run ${RUN_ID}; launch is still in progress (dispatching).`
},
{ status: 'dispatched', acknowledgement: `Started run ${RUN_ID} (dispatched).` },
{ status: 'completed', acknowledgement: `Completed run ${RUN_ID}.` },
{ status: 'dispatch_failed', acknowledgement: `Run ${RUN_ID} failed (dispatch_failed).` },
{
status: 'skipped_unavailable',
acknowledgement: `Skipped run ${RUN_ID} (skipped_unavailable).`
},
{
status: 'skipped_precheck',
acknowledgement: `Skipped run ${RUN_ID} (skipped_precheck).`
},
{
status: 'skipped_missed',
acknowledgement: `Skipped run ${RUN_ID} (skipped_missed).`
},
{
status: 'skipped_needs_interactive_auth',
acknowledgement: `Skipped run ${RUN_ID} (skipped_needs_interactive_auth).`
}
] as const)(
'prints the authoritative $status outcome without unknown handles',
async ({ status, acknowledgement }) => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const error = status === 'dispatch_failed' ? 'Agent launch failed.' : null
queueRun(run({ status, error }))
await main(['automations', 'run', AUTOMATION_ID], '/tmp/repo')
expect(log).toHaveBeenCalledExactlyOnceWith(
[
acknowledgement,
`id: ${RUN_ID}`,
`automationId: ${AUTOMATION_ID}`,
'title: Daily checks run 1',
`status: ${status}`,
'trigger: manual',
'scheduledFor: 1970-01-01T00:00:00.000Z',
...(error ? [`error: ${error}`] : []),
`Follow up: orca automations runs --id ${AUTOMATION_ID}`
].join('\n')
)
expect(callMock).toHaveBeenCalledTimes(2)
expect(callMock).toHaveBeenNthCalledWith(2, 'automation.runNow', { id: AUTOMATION_ID })
}
)
it('prints workspace and terminal identities only when supplied by the host', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
queueRun(
run({
status: 'dispatched',
workspaceId: 'folder:workspace-1',
terminalSessionId: 'tab-1',
terminalPaneKey: 'tab-1:leaf-1',
terminalPtyId: 'pty-1'
})
)
await main(['automations', 'run', AUTOMATION_ID], '/tmp/repo')
expect(log).toHaveBeenCalledExactlyOnceWith(
[
`Started run ${RUN_ID} (dispatched).`,
`id: ${RUN_ID}`,
`automationId: ${AUTOMATION_ID}`,
'title: Daily checks run 1',
'status: dispatched',
'trigger: manual',
'scheduledFor: 1970-01-01T00:00:00.000Z',
'workspaceId: folder:workspace-1',
'terminalSessionId: tab-1',
'terminalPaneKey: tab-1:leaf-1',
'terminalPtyId: pty-1',
`Follow up: orca automations runs --id ${AUTOMATION_ID}`
].join('\n')
)
})
it('preserves the supplied precheck and error on a skipped run', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
queueRun(
run({
status: 'skipped_precheck',
error: 'Precheck exited with code 1.',
precheckResult: {
command: 'test -f ready',
exitCode: 1,
timedOut: false,
durationMs: 1,
stdout: '',
stderr: 'Not ready',
stdoutTruncated: false,
stderrTruncated: false,
error: null,
startedAt: 0,
completedAt: 1
}
})
)
await main(['automations', 'run', AUTOMATION_ID], '/tmp/repo')
expect(log).toHaveBeenCalledExactlyOnceWith(
[
`Skipped run ${RUN_ID} (skipped_precheck).`,
`id: ${RUN_ID}`,
`automationId: ${AUTOMATION_ID}`,
'title: Daily checks run 1',
'status: skipped_precheck',
'trigger: manual',
'scheduledFor: 1970-01-01T00:00:00.000Z',
'precheck: exit 1; Not ready',
'error: Precheck exited with code 1.',
`Follow up: orca automations runs --id ${AUTOMATION_ID}`
].join('\n')
)
})
it.each([
'pending',
'dispatching',
'dispatched',
'dispatch_failed',
'skipped_unavailable'
] as const)('adds a JSON runId while retaining the %s run and RPC metadata', async (status) => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const result = run({ status })
queueRun(result)
await main(['automations', 'run', AUTOMATION_ID, '--json'], '/tmp/repo')
const output = String(log.mock.calls[0]?.[0])
expect(JSON.parse(output)).toEqual(okFixture('req_run', { run: result, runId: RUN_ID }))
})
it('prints no acknowledgment until the host returns a delayed result', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
queueFixtures(callMock, okFixture('req_owner', { automation: { id: AUTOMATION_ID } }))
@@ -262,101 +129,6 @@ describe('automation run command output', () => {
)
})
it('supports old host responses that omit terminal identity fields', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const { terminalPaneKey: _pane, terminalPtyId: _pty, ...legacyRun } = run()
queueFixtures(
callMock,
okFixture('req_owner', { automation: { id: AUTOMATION_ID } }),
okFixture('req_run', { run: legacyRun })
)
await main(['automations', 'run', AUTOMATION_ID, '--json'], '/tmp/repo')
expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toEqual(
okFixture('req_run', { run: legacyRun, runId: RUN_ID })
)
})
it('prints an unfamiliar newer-host status without claiming the run started', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
queueFixtures(
callMock,
okFixture('req_owner', { automation: { id: AUTOMATION_ID } }),
okFixture('req_run', { run: { ...run(), status: 'future_status' } })
)
await main(['automations', 'run', AUTOMATION_ID], '/tmp/repo')
expect(String(log.mock.calls[0]?.[0]).split('\n')[0]).toBe(`Run ${RUN_ID}: future_status.`)
})
it('preserves the SSH owner fence while adding the runId', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const owner = { selector: { kind: 'ssh', targetId: 'ssh-1', targetGeneration: 3 } }
queueFixtures(
callMock,
okFixture('req_owner', { automation: { id: AUTOMATION_ID }, owner }),
okFixture('req_run', { run: run() })
)
await main(['automations', 'run', AUTOMATION_ID, '--json'], '/tmp/repo')
expect(callMock).toHaveBeenNthCalledWith(2, 'automation.runNow', {
id: AUTOMATION_ID,
expectedOwner: owner
})
expect(JSON.parse(String(log.mock.calls[0]?.[0])).result.runId).toBe(RUN_ID)
})
it.each(['explicit', 'ambient'] as const)(
'preserves the %s environment in the follow-up command',
async (selection) => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
pairRuntimeEnvironment(listEnvironmentsMock, 'env-build', 'Build server')
const flags = selection === 'explicit' ? ['--environment', 'Build server'] : []
process.env.ORCA_ENVIRONMENT = selection === 'explicit' ? 'wrong-host' : 'Build server'
queueRun(run())
await main(['automations', 'run', AUTOMATION_ID, ...flags], '/tmp/repo')
const quotedEnvironment = process.platform === 'win32' ? '"Build server"' : "'Build server'"
const output = String(log.mock.calls[0]?.[0])
expect(output.split('\n').at(-1)).toBe(
`Follow up: orca automations runs --id ${AUTOMATION_ID} --environment ${quotedEnvironment}`
)
expect(output).not.toContain('wrong-host')
expect(callMock).toHaveBeenNthCalledWith(2, 'automation.runNow', { id: AUTOMATION_ID })
}
)
it.each(['$box', '%box%', 'a`b', 'a"b', 'has!bang', 'back\\slash'])(
'requires same-target guidance for the Windows shell-sensitive label %s',
async (environment) => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
pairRuntimeEnvironment(listEnvironmentsMock, 'env-build', environment)
queueRun(run())
await main(['automations', 'run', AUTOMATION_ID, '--environment', environment], '/tmp/repo')
expect(String(log.mock.calls[0]?.[0]).split('\n').at(-1)).toBe(
`Follow up on the same host and profile (preserve your connection/profile settings): orca automations runs --id ${AUTOMATION_ID}`
)
}
)
it('requires same-target guidance for a label that would parse as another flag', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
pairRuntimeEnvironment(listEnvironmentsMock, 'env-build', '--build')
queueRun(run())
await main(['automations', 'run', AUTOMATION_ID, '--environment=--build'], '/tmp/repo')
expect(String(log.mock.calls[0]?.[0]).split('\n').at(-1)).toBe(
`Follow up on the same host and profile (preserve your connection/profile settings): orca automations runs --id ${AUTOMATION_ID}`
)
})
it('quotes an expansion-sensitive environment literally for POSIX shells', async () => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
pairRuntimeEnvironment(listEnvironmentsMock, 'env-build', '$box')
queueRun(run())
await main(['automations', 'run', AUTOMATION_ID, '--environment', '$box'], '/tmp/repo')
expect(String(log.mock.calls[0]?.[0]).split('\n').at(-1)).toBe(
`Follow up: orca automations runs --id ${AUTOMATION_ID} --environment '$box'`
)
})
it.each(['explicit', 'ORCA_PAIRING_CODE', 'ORCA_REMOTE_PAIRING'] as const)(
'requires the same target without exposing %s pairing credentials',
async (selection) => {
@@ -380,52 +152,4 @@ describe('automation run command output', () => {
expect(log.mock.calls.flat().join('\n')).not.toContain(pairingCode)
}
)
it.each([false, true])(
'requires the same custom profile with environment selection %s',
async (withEnvironment) => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
process.env.ORCA_USER_DATA_PATH = '/tmp/nondefault profile'
const flags = withEnvironment ? ['--environment', 'build'] : []
pairRuntimeEnvironment(listEnvironmentsMock, 'env-build', 'build')
queueRun(run())
await main(['automations', 'run', AUTOMATION_ID, ...flags], '/tmp/repo')
const output = String(log.mock.calls[0]?.[0])
expect(output.split('\n').at(-1)).toBe(
`Follow up on the same host and profile (preserve your connection/profile settings): orca automations runs --id ${AUTOMATION_ID}${withEnvironment ? ' --environment build' : ''}`
)
expect(output).not.toContain('/tmp/nondefault profile')
expect(callMock).toHaveBeenCalledTimes(2)
}
)
it('rejects the unsupported --user-data-dir flag before selecting a runtime', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const previousExitCode = process.exitCode
try {
await main(
['automations', 'run', AUTOMATION_ID, '--user-data-dir', '/tmp/other-profile', '--json'],
'/tmp/repo'
)
const output = JSON.parse(String(log.mock.calls[0]?.[0]))
expect(output).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(output.error.message).toContain('--user-data-dir')
expect(callMock).not.toHaveBeenCalled()
} finally {
process.exitCode = previousExitCode
}
})
it('explains full UUIDs and pending launch behavior in run help', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await main(['automations', 'run', '--help'], '/tmp/repo')
expect(String(log.mock.calls[0]?.[0])).toContain(
'Use the full automation UUID from orca automations list; shortened prefixes are not accepted.'
)
expect(String(log.mock.calls[0]?.[0])).toContain(
'A queued or dispatching run has been accepted'
)
expect(String(log.mock.calls[0]?.[0])).toContain(`orca automations run ${AUTOMATION_ID}`)
expect(callMock).not.toHaveBeenCalled()
})
})
-478
View File
@@ -1,478 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
const {
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
} = vi.hoisted(() => ({
callMock: vi.fn(),
runtimeClientConstructorMock: vi.fn(),
serveOrcaAppMock: vi.fn(),
getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'),
addEnvironmentFromPairingCodeMock: vi.fn(),
listEnvironmentsMock: vi.fn(),
spawnMock: vi.fn()
}))
vi.mock('./runtime-client', async () => {
const { createRuntimeClientModuleMock } = await import('./index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock
})
})
vi.mock('./runtime/environments', () => ({
addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock,
removeEnvironment: vi.fn(),
resolveEnvironment: vi.fn()
}))
vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: listEnvironmentsMock
}))
vi.mock('child_process', async () => {
const { createChildProcessModuleMock } = await import('./index-test-harness.js')
return createChildProcessModuleMock(spawnMock)
})
import { main } from './index'
import {
buildWorktree,
localRepoDestinationFixtures,
okFixture,
queueFixtures,
workspaceDestinationFixtures,
worktreeListFixture
} from './test-fixtures'
import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness'
describe('orca cli worktree awareness', () => {
const originalExitCode = process.exitCode
afterEach(() => {
process.exitCode = originalExitCode
})
useWorktreeAwarenessEnvironment({
callMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
})
it('creates an automation for the enclosing worktree by default', async () => {
queueFixtures(
callMock,
worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo', 'abc', 'repo-1')]),
...workspaceDestinationFixtures(),
okFixture('req_automation_create', {
automation: {
id: 'auto-1',
name: 'Daily review',
prompt: 'Review open changes',
agentId: 'codex',
projectId: 'repo-1',
executionTargetType: 'local',
executionTargetId: 'local',
schedulerOwner: 'local_host_service',
workspaceMode: 'existing',
workspaceId: 'repo-1::/tmp/repo/feature',
baseBranch: null,
timezone: 'America/Toronto',
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: 1,
enabled: true,
nextRunAt: 2,
missedRunPolicy: 'run_once_within_grace',
missedRunGraceMinutes: 720,
createdAt: 1,
updatedAt: 1
}
})
)
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
[
'automations',
'create',
'--name',
'Daily review',
'--trigger',
'daily',
'--prompt',
'Review open changes',
'--provider',
'codex',
'--json'
],
'/tmp/repo/feature/src'
)
expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', {
limit: 10_000
})
expect(callMock).toHaveBeenNthCalledWith(4, 'automation.create', {
name: 'Daily review',
prompt: 'Review open changes',
precheck: undefined,
agentId: 'codex',
repo: undefined,
workspace: 'id:repo-1::/tmp/repo/feature',
workspaceMode: 'existing',
baseBranch: undefined,
reuseSession: undefined,
timezone: undefined,
enabled: undefined,
missedRunGraceMinutes: undefined,
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: expect.any(Number),
destination: { selector: { kind: 'self' } }
})
})
it('resolves project and host flags for automation create', async () => {
pairRuntimeEnvironment(listEnvironmentsMock, 'gpu')
queueFixtures(
callMock,
okFixture('req_project_setups', {
setups: [
{
id: 'setup-local',
projectId: 'github:stablyai/orca',
hostId: 'local',
repoId: 'repo-local',
path: '/tmp/orca',
displayName: 'Orca',
setupState: 'ready',
setupMethod: 'legacy-repo',
createdAt: 1,
updatedAt: 1
},
{
id: 'setup-gpu',
projectId: 'github:stablyai/orca',
hostId: 'runtime:gpu',
repoId: 'repo-gpu',
path: '/srv/orca',
displayName: 'Orca',
setupState: 'ready',
setupMethod: 'legacy-repo',
createdAt: 1,
updatedAt: 1
}
]
}),
...localRepoDestinationFixtures('repo-gpu'),
okFixture('req_automation_create', {
automation: { id: 'auto-1', name: 'GPU review' }
})
)
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
[
'automations',
'create',
'--name',
'GPU review',
'--trigger',
'daily',
'--prompt',
'Review open changes',
'--provider',
'codex',
'--project',
'github:stablyai/orca',
'--host',
'runtime:gpu',
'--json'
],
'/tmp/repo'
)
expect(runtimeClientConstructorMock).toHaveBeenCalledWith(null, 'gpu')
expect(callMock).toHaveBeenNthCalledWith(1, 'projectHostSetup.list')
expect(callMock).toHaveBeenNthCalledWith(
3,
'automation.create',
expect.objectContaining({
repo: 'id:repo-gpu',
runContext: {
kind: 'workspace-run',
projectId: 'github:stablyai/orca',
hostId: 'runtime:gpu',
projectHostSetupId: 'setup-gpu',
repoId: 'repo-gpu',
path: '/srv/orca'
},
workspace: undefined,
workspaceMode: 'new_per_run'
})
)
})
it('resolves project-host-setup flags for automation edit with explicit run context', async () => {
queueFixtures(
callMock,
okFixture('req_project_setups', {
setups: [
{
id: 'setup-gpu',
projectId: 'github:stablyai/orca',
hostId: 'runtime:gpu',
repoId: 'repo-gpu',
path: '/srv/orca',
displayName: 'Orca',
setupState: 'ready',
setupMethod: 'legacy-repo',
createdAt: 1,
updatedAt: 1
}
]
}),
okFixture('req_edit_owner', { automation: { id: 'auto-1', name: 'GPU review' } }),
...localRepoDestinationFixtures('repo-gpu'),
okFixture('req_edit', {
automation: { id: 'auto-1', name: 'GPU review' }
})
)
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
['automations', 'edit', 'auto-1', '--project-host-setup', 'setup-gpu', '--json'],
'/tmp/repo'
)
expect(callMock).toHaveBeenNthCalledWith(1, 'projectHostSetup.list')
expect(callMock).toHaveBeenNthCalledWith(
4,
'automation.update',
expect.objectContaining({
id: 'auto-1',
updates: expect.objectContaining({
repo: 'id:repo-gpu',
runContext: {
kind: 'workspace-run',
projectId: 'github:stablyai/orca',
hostId: 'runtime:gpu',
projectHostSetupId: 'setup-gpu',
repoId: 'repo-gpu',
path: '/srv/orca'
}
})
})
)
})
it('rejects automation create with both repo and workspace targets', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
[
'automations',
'create',
'--name',
'Daily review',
'--trigger',
'daily',
'--prompt',
'Review open changes',
'--provider',
'codex',
'--repo',
'id:repo-1',
'--workspace',
'id:repo-1::/tmp/repo/feature',
'--json'
],
'/tmp/repo'
)
expect(callMock).not.toHaveBeenCalled()
expect(logSpy).toHaveBeenCalledTimes(1)
expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: expect.stringContaining('Use either --repo or --workspace, not both.')
}
})
expect(process.exitCode).toBe(1)
})
it('rejects automation edit with both repo and workspace targets', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
[
'automations',
'edit',
'auto-1',
'--repo',
'id:repo-1',
'--workspace',
'id:repo-1::/tmp/repo/feature',
'--json'
],
'/tmp/repo'
)
expect(callMock).not.toHaveBeenCalled()
expect(logSpy).toHaveBeenCalledTimes(1)
expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: expect.stringContaining('Use either --repo or --workspace, not both.')
}
})
expect(process.exitCode).toBe(1)
})
it.each([
{
flag: 'enabled',
value: 'false',
message: '--enabled does not take a value'
},
{
flag: 'disabled',
value: 'false',
message: '--disabled does not take a value'
}
])('rejects automation create --$flag with a string value', async ({ flag, value, message }) => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
[
'automations',
'create',
'--name',
'Daily review',
'--trigger',
'daily',
'--prompt',
'Review open changes',
'--provider',
'codex',
'--repo',
'id:repo-1',
`--${flag}`,
value,
'--json'
],
'/tmp/repo'
)
expect(callMock).not.toHaveBeenCalled()
expect(logSpy).toHaveBeenCalledTimes(1)
expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toMatchObject({
ok: false,
error: { code: 'invalid_argument', message: expect.stringContaining(message) }
})
expect(process.exitCode).toBe(1)
})
it('resolves explicit automation create workspace active from cwd', async () => {
queueFixtures(
callMock,
worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo', 'abc', 'repo-1')]),
...workspaceDestinationFixtures(),
okFixture('req_automation_create', {
automation: { id: 'auto-1', name: 'Daily review' }
})
)
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
[
'automations',
'create',
'--name',
'Daily review',
'--trigger',
'daily',
'--prompt',
'Review open changes',
'--provider',
'codex',
'--workspace',
'active',
'--json'
],
'/tmp/repo/feature/src'
)
expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', {
limit: 10_000
})
expect(callMock).toHaveBeenNthCalledWith(4, 'automation.create', {
name: 'Daily review',
prompt: 'Review open changes',
precheck: undefined,
agentId: 'codex',
repo: undefined,
workspace: 'id:repo-1::/tmp/repo/feature',
workspaceMode: 'existing',
baseBranch: undefined,
timezone: undefined,
enabled: undefined,
missedRunGraceMinutes: undefined,
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
dtstart: expect.any(Number),
reuseSession: undefined,
destination: { selector: { kind: 'self' } }
})
})
it('resolves explicit automation edit workspace current from cwd', async () => {
queueFixtures(
callMock,
worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo', 'abc', 'repo-1')]),
okFixture('req_edit_owner', { automation: { id: 'auto-1', name: 'Daily review' } }),
...workspaceDestinationFixtures(),
okFixture('req_edit', {
automation: { id: 'auto-1', name: 'Daily review' }
})
)
vi.spyOn(console, 'log').mockImplementation(() => {})
await main(
['automations', 'edit', 'auto-1', '--workspace', 'current', '--enabled', '--json'],
'/tmp/repo/feature/src'
)
expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', {
limit: 10_000
})
expect(callMock).toHaveBeenNthCalledWith(5, 'automation.update', {
id: 'auto-1',
updates: {
name: undefined,
prompt: undefined,
precheck: undefined,
agentId: undefined,
repo: undefined,
workspace: 'id:repo-1::/tmp/repo/feature',
workspaceMode: undefined,
baseBranch: undefined,
reuseSession: undefined,
timezone: undefined,
enabled: true,
missedRunGraceMinutes: undefined
},
destination: { selector: { kind: 'self' } }
})
})
})