Harden computer use runtime and CLI (#4705)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-06-07 17:49:01 -07:00
committed by GitHub
co-authored by Orca
parent 401fc1e43e
commit 76cb846d68
96 changed files with 10408 additions and 3410 deletions
+65 -5
View File
@@ -6,18 +6,30 @@ on:
- '.github/workflows/computer-e2e.yml'
- 'config/electron-builder.config.cjs'
- 'config/scripts/build-computer-macos.mjs'
- 'config/scripts/computer-e2e-workflow.test.mjs'
- 'config/scripts/computer-use-skill-guidance.test.mjs'
- 'config/scripts/computer-use-smoke.mjs'
- 'config/scripts/computer-use-smoke.test.mjs'
- 'config/scripts/verify-computer-native.mjs'
- 'native/computer-use-macos/**'
- 'native/computer-use-linux/**'
- 'native/computer-use-windows/**'
- 'skills/computer-use/SKILL.md'
- 'src/cli/**'
- 'src/main/computer/**'
- 'src/main/runtime/rpc/methods/computer.ts'
- 'src/main/runtime/rpc/dispatcher.ts'
- 'src/main/runtime/rpc/errors.ts'
- 'src/main/runtime/rpc/methods/computer*.ts'
- 'src/shared/computer-use-*.ts'
- 'src/shared/runtime-types.ts'
- 'tests/e2e/computer-linux.e2e.ts'
- 'tests/e2e/computer-mac.e2e.ts'
- 'tests/e2e/computer-mac-safari.e2e.ts'
- 'tests/e2e/computer-windows.e2e.ts'
- 'tests/e2e/computer-windows-store.e2e.ts'
- 'tests/e2e/helpers/computer-cli-driver.ts'
- 'tests/e2e/helpers/computer-driver.ts'
- 'tests/e2e/vitest.config.ts'
workflow_dispatch:
schedule:
- cron: '0 6 * * *'
@@ -25,6 +37,8 @@ on:
jobs:
native-smoke:
if: github.event_name == 'pull_request'
permissions:
contents: read
strategy:
fail-fast: false
matrix:
@@ -39,7 +53,7 @@ jobs:
with:
run_install: false
- if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y python3 python3-gi gir1.2-atspi-2.0 at-spi2-core xclip xdotool
run: sudo apt-get update && sudo apt-get install -y python3 python3-gi gir1.2-atspi-2.0 at-spi2-core gedit xvfb xclip xdotool
# Why: pnpm's bundled node-gyp can ship gyp_main.py without execute
# permission on Linux runners; node-pty's install fallback then fails
# before this smoke job can exercise the native package.
@@ -49,8 +63,51 @@ jobs:
npm install -g node-gyp@11.5.0
echo "npm_config_node_gyp=$(npm root -g)/node-gyp/bin/node-gyp.js" >> "$GITHUB_ENV"
- run: pnpm install --frozen-lockfile
- run: >-
pnpm vitest run
config/scripts/computer-e2e-workflow.test.mjs
config/scripts/computer-use-skill-guidance.test.mjs
config/scripts/computer-use-smoke.test.mjs
src/main/computer/computer-provider-lifecycle.test.ts
src/main/computer/computer-provider-unavailable-message.test.ts
src/main/computer/sidecar-client.test.ts
src/main/computer/macos-native-provider-client.test.ts
src/main/computer/macos-native-provider-socket.test.ts
src/main/computer/macos-computer-use-permissions.test.ts
src/main/computer/macos-computer-use-permission-status.test.ts
src/main/computer/desktop-script-provider-client.test.ts
src/main/computer/desktop-script-provider-cache.test.ts
src/main/computer/desktop-script-provider-actions.test.ts
src/main/computer/desktop-script-provider-cache-lifecycle.test.ts
src/main/computer/desktop-script-provider-errors.test.ts
src/main/computer/desktop-script-provider-action-errors.test.ts
src/shared/computer-use-error-recovery.test.ts
src/shared/computer-use-key-spec.test.ts
src/cli/format.test.ts
src/cli/handlers/computer.test.ts
src/cli/handlers/computer-action-routing.test.ts
src/cli/handlers/computer-action-validation.test.ts
src/cli/handlers/computer-state-formatting.test.ts
src/cli/specs/computer.test.ts
src/cli/index.test.ts
src/main/runtime/rpc/dispatcher-computer-errors.test.ts
src/main/runtime/rpc/errors.test.ts
src/main/runtime/rpc/methods/computer.test.ts
src/main/runtime/rpc/methods/computer-actions.test.ts
src/cli/runtime/envelope-schema.test.ts
src/shared/remote-runtime-client.test.ts
- run: pnpm verify:computer-native
- run: pnpm build:cli
- run: pnpm build:electron-vite
- if: runner.os == 'Linux'
env:
ORCA_COMPUTER_E2E: '1'
ACCESSIBILITY_ENABLED: '1'
run: xvfb-run --auto-servernum dbus-run-session -- pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-linux.e2e.ts
- if: runner.os == 'Windows'
env:
ORCA_COMPUTER_E2E: '1'
run: pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts
mac:
# macOS Accessibility and Screen Recording require user-granted TCC entries.
@@ -71,7 +128,8 @@ jobs:
- run: pnpm build:computer-macos
- run: pnpm verify:computer-native
- run: pnpm build:cli
- run: pnpm test:e2e:computer -- --reporter=verbose tests/e2e/computer-mac.e2e.ts
- run: pnpm build:electron-vite
- run: pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-mac.e2e.ts tests/e2e/computer-mac-safari.e2e.ts
linux:
if: github.event_name != 'pull_request'
@@ -97,7 +155,8 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm verify:computer-native
- run: pnpm build:cli
- run: xvfb-run --auto-servernum dbus-run-session -- pnpm test:e2e:computer -- --reporter=verbose tests/e2e/computer-linux.e2e.ts
- run: pnpm build:electron-vite
- run: xvfb-run --auto-servernum dbus-run-session -- pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-linux.e2e.ts
windows:
if: github.event_name != 'pull_request'
@@ -115,4 +174,5 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm verify:computer-native
- run: pnpm build:cli
- run: pnpm test:e2e:computer -- --reporter=verbose tests/e2e/computer-windows.e2e.ts
- run: pnpm build:electron-vite
- run: pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts tests/e2e/computer-windows-store.e2e.ts
@@ -0,0 +1,225 @@
import { readFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { parse } from 'yaml'
const projectDir = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
describe('computer-use e2e workflow', () => {
it('runs computer-use e2e files serially because they share desktop focus', () => {
const config = readFileSync(join(projectDir, 'tests/e2e/vitest.config.ts'), 'utf8')
expect(config).toContain('fileParallelism: false')
})
it('guards e2e source against fragile fixed waits and stale element indexes', () => {
const driver = readFileSync(join(projectDir, 'tests/e2e/helpers/computer-driver.ts'), 'utf8')
const cliDriver = readFileSync(
join(projectDir, 'tests/e2e/helpers/computer-cli-driver.ts'),
'utf8'
)
const windowsStoreE2e = readFileSync(
join(projectDir, 'tests/e2e/computer-windows-store.e2e.ts'),
'utf8'
)
expect(driver).not.toContain('await delay(3500)')
expect(driver).toContain("await waitForComputerWindowTitle('gedit', fileName, 15000)")
expect(cliDriver).toContain('ORCA_DEV_USER_DATA_PATH')
expect(cliDriver).toContain('orca-computer-runtime-')
expect(cliDriver).toContain('retryMissingRuntimeMetadata')
expect(cliDriver).toContain('Could not read Orca runtime metadata')
expect(cliDriver).toContain("'serve', '--no-pairing', '--json'")
expect(windowsStoreE2e).toMatch(
/for \(const buttonName of \['One', 'Plus', 'Two', 'Equals'\]\) \{[\s\S]*findRoleIndex\(state\.result\.snapshot\.treeText, `button \$\{buttonName\}`\)[\s\S]*state = parseJsonOutput/
)
expect(windowsStoreE2e).not.toMatch(/const one = findRoleIndex/)
expect(windowsStoreE2e).not.toMatch(/for \(const index of \[one, plus, two, equals\]\)/)
})
it('triggers on computer-use shared contracts, scripts, and agent skill changes', () => {
const workflow = parse(
readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8')
)
const triggerPaths = workflow.on.pull_request.paths
expect(triggerPaths).toEqual(
expect.arrayContaining([
'config/scripts/computer-e2e-workflow.test.mjs',
'config/scripts/computer-use-skill-guidance.test.mjs',
'config/scripts/computer-use-smoke.mjs',
'config/scripts/computer-use-smoke.test.mjs',
'skills/computer-use/SKILL.md',
'src/main/computer/**',
'src/main/runtime/rpc/dispatcher.ts',
'src/main/runtime/rpc/errors.ts',
'src/main/runtime/rpc/methods/computer*.ts',
'src/shared/computer-use-*.ts',
'tests/e2e/vitest.config.ts'
])
)
})
it('runs focused computer-use regression tests in the PR native-smoke job', () => {
const workflow = parse(
readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8')
)
const nativeSmokeRuns = workflow.jobs['native-smoke'].steps
.map((step) => step.run)
.filter((run) => typeof run === 'string')
const regressionRun = nativeSmokeRuns.find((run) => run.includes('pnpm vitest run'))
const expectedRegressionFiles = [
'config/scripts/computer-e2e-workflow.test.mjs',
'config/scripts/computer-use-skill-guidance.test.mjs',
'config/scripts/computer-use-smoke.test.mjs',
'src/main/computer/computer-provider-lifecycle.test.ts',
'src/main/computer/computer-provider-unavailable-message.test.ts',
'src/main/computer/sidecar-client.test.ts',
'src/main/computer/macos-native-provider-client.test.ts',
'src/main/computer/macos-native-provider-socket.test.ts',
'src/main/computer/macos-computer-use-permissions.test.ts',
'src/main/computer/macos-computer-use-permission-status.test.ts',
'src/main/computer/desktop-script-provider-client.test.ts',
'src/main/computer/desktop-script-provider-cache.test.ts',
'src/main/computer/desktop-script-provider-actions.test.ts',
'src/main/computer/desktop-script-provider-cache-lifecycle.test.ts',
'src/main/computer/desktop-script-provider-errors.test.ts',
'src/main/computer/desktop-script-provider-action-errors.test.ts',
'src/shared/computer-use-error-recovery.test.ts',
'src/shared/computer-use-key-spec.test.ts',
'src/cli/format.test.ts',
'src/cli/handlers/computer.test.ts',
'src/cli/handlers/computer-action-routing.test.ts',
'src/cli/handlers/computer-action-validation.test.ts',
'src/cli/handlers/computer-state-formatting.test.ts',
'src/cli/specs/computer.test.ts',
'src/cli/index.test.ts',
'src/main/runtime/rpc/dispatcher-computer-errors.test.ts',
'src/main/runtime/rpc/errors.test.ts',
'src/main/runtime/rpc/methods/computer.test.ts',
'src/main/runtime/rpc/methods/computer-actions.test.ts',
'src/cli/runtime/envelope-schema.test.ts',
'src/shared/remote-runtime-client.test.ts'
]
expect(regressionRun).toBeTruthy()
for (const file of expectedRegressionFiles) {
expect(regressionRun).toContain(file)
}
})
it('runs Linux computer-use e2e in the PR native-smoke job under Xvfb', () => {
const workflow = parse(
readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8')
)
const nativeSmokeRuns = workflow.jobs['native-smoke'].steps
.map((step) => step.run)
.filter((run) => typeof run === 'string')
const installRun = nativeSmokeRuns.find((run) => run.includes('apt-get install'))
expect(installRun).toContain('gedit')
expect(installRun).toContain('xvfb')
expect(nativeSmokeRuns).toContain(
'xvfb-run --auto-servernum dbus-run-session -- pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-linux.e2e.ts'
)
})
it('builds Electron main output before every computer-use e2e run', () => {
const workflow = parse(
readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8')
)
for (const jobName of ['native-smoke', 'mac', 'linux', 'windows']) {
const runs = workflow.jobs[jobName].steps
.map((step) => step.run)
.filter((run) => typeof run === 'string')
const buildIndex = runs.indexOf('pnpm build:electron-vite')
const e2eIndexes = runs
.map((run, index) => (run.includes('test:e2e:computer') ? index : -1))
.filter((index) => index >= 0)
expect(
buildIndex,
`${jobName} should build out/main before computer e2e`
).toBeGreaterThanOrEqual(0)
for (const e2eIndex of e2eIndexes) {
expect(buildIndex, `${jobName} should build out/main before computer e2e`).toBeLessThan(
e2eIndex
)
}
}
})
it('runs core Windows computer-use e2e in the PR native-smoke job', () => {
const workflow = parse(
readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8')
)
const nativeSmokeRuns = workflow.jobs['native-smoke'].steps
.map((step) => step.run)
.filter((run) => typeof run === 'string')
const allRuns = [
...nativeSmokeRuns,
...workflow.jobs.mac.steps.map((step) => step.run).filter((run) => typeof run === 'string'),
...workflow.jobs.linux.steps.map((step) => step.run).filter((run) => typeof run === 'string'),
...workflow.jobs.windows.steps
.map((step) => step.run)
.filter((run) => typeof run === 'string')
]
expect(nativeSmokeRuns).toContain(
'pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts'
)
expect(allRuns.join('\n')).not.toContain('test:e2e:computer -- --reporter')
})
it('runs macOS and Linux computer-use e2e files in scheduled jobs', () => {
const workflow = parse(
readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8')
)
const triggerPaths = workflow.on.pull_request.paths
const macRuns = workflow.jobs.mac.steps
.map((step) => step.run)
.filter((run) => typeof run === 'string')
const linuxRuns = workflow.jobs.linux.steps
.map((step) => step.run)
.filter((run) => typeof run === 'string')
expect(triggerPaths).toEqual(
expect.arrayContaining([
'tests/e2e/computer-mac.e2e.ts',
'tests/e2e/computer-mac-safari.e2e.ts',
'tests/e2e/computer-linux.e2e.ts',
'tests/e2e/helpers/computer-cli-driver.ts',
'tests/e2e/helpers/computer-driver.ts'
])
)
expect(macRuns).toContain(
'pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-mac.e2e.ts tests/e2e/computer-mac-safari.e2e.ts'
)
expect(linuxRuns).toContain(
'xvfb-run --auto-servernum dbus-run-session -- pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-linux.e2e.ts'
)
})
it('runs every Windows computer-use e2e file in the scheduled Windows job', () => {
const workflow = parse(
readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8')
)
const triggerPaths = workflow.on.pull_request.paths
const windowsRuns = workflow.jobs.windows.steps
.map((step) => step.run)
.filter((run) => typeof run === 'string')
expect(triggerPaths).toEqual(
expect.arrayContaining([
'tests/e2e/computer-windows.e2e.ts',
'tests/e2e/computer-windows-store.e2e.ts'
])
)
expect(windowsRuns).toContain(
'pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts tests/e2e/computer-windows-store.e2e.ts'
)
})
})
@@ -0,0 +1,37 @@
import { readFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
const projectDir = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
const skillPath = join(projectDir, 'skills', 'computer-use', 'SKILL.md')
describe('computer-use skill guidance', () => {
it('keeps web-app targeting on the computer-use surface', () => {
const skill = readFileSync(skillPath, 'utf8')
expect(skill).toContain('Use this skill for desktop UI through `orca computer`')
expect(skill).toContain('operate the desktop browser app/window that contains the page')
expect(skill).not.toContain('orca goto')
expect(skill).not.toContain('orca snapshot')
expect(skill).not.toContain('orca click')
expect(skill).not.toContain('orca fill')
expect(skill).not.toContain('Routing:')
})
it('warns agents to verify browser-hosted form focus before drafting text', () => {
const skill = readFileSync(skillPath, 'utf8')
expect(skill).toContain('For browser-hosted forms such as Gmail compose')
expect(skill).toContain('verify the focused UI element after each field action')
expect(skill).toContain('Prefer `paste-text` into the verified focused field')
})
it('warns agents about occluded Linux and Windows screenshots', () => {
const skill = readFileSync(skillPath, 'utf8')
expect(skill).toContain('On Linux and Windows')
expect(skill).toContain('use `--restore-window` so another window does not cover')
expect(skill).toContain('trust the tree over potentially occluded pixels')
})
})
+62 -16
View File
@@ -6,15 +6,18 @@ import { resolve } from 'node:path'
import { spawnSync } from 'node:child_process'
const repoRoot = resolve(import.meta.dirname, '..', '..')
const cliPath = resolve(repoRoot, 'out', 'cli', 'index.js')
const cliPath =
process.env.ORCA_COMPUTER_SMOKE_CLI_PATH ?? resolve(repoRoot, 'out', 'cli', 'index.js')
const args = new Set(process.argv.slice(2))
const requestedApps = valueFlag('--apps')
const includeScreenshot = args.has('--screenshot')
const launchRuntime = args.has('--launch')
const requireTarget = args.has('--require-target')
const session = valueFlag('--session') ?? `computer-smoke-${process.pid}`
const preferredApps = (
requestedApps ??
process.env.ORCA_COMPUTER_SMOKE_APPS ??
'Finder,TextEdit,Spotify,Slack,Microsoft Edge'
'Finder,TextEdit,Text Editor,gedit,Notepad,Calculator,Microsoft Edge,Google Chrome,Safari,Slack,Spotify'
)
.split(',')
.map((app) => app.trim())
@@ -24,6 +27,13 @@ if (!existsSync(cliPath)) {
fail(`Missing built CLI at ${cliPath}. Run pnpm build:cli first.`)
}
if (launchRuntime) {
const opened = unwrapResult(runCli(['open', '--json']))
console.log(
`computer-use smoke: runtime ${opened.runtime?.state ?? 'unknown'} (${opened.runtime?.runtimeId ?? 'unknown'})`
)
}
const list = unwrapResult(runCli(['computer', 'list-apps', '--json']))
const apps = Array.isArray(list.apps) ? list.apps : []
const availableNames = new Set(apps.map((app) => String(app.name ?? '').toLowerCase()))
@@ -36,31 +46,29 @@ const targets = preferredApps.filter(
console.log(`computer-use smoke: ${apps.length} apps listed`)
if (targets.length === 0) {
console.log(`computer-use smoke: no preferred apps are running (${preferredApps.join(', ')})`)
const message = `no preferred apps are running (${preferredApps.join(', ')})`
if (requireTarget) {
fail(message)
}
console.log(`computer-use smoke: ${message}`)
process.exit(0)
}
let failures = 0
let successes = 0
for (const app of targets) {
const result = runCli(
[
'computer',
'get-app-state',
'--session',
session,
'--app',
app,
...(includeScreenshot ? [] : ['--no-screenshot']),
'--json'
],
{ allowFailure: true }
)
const result = runSnapshotSmoke(app)
if (!result.ok) {
if (result.skipped) {
console.log(`computer-use smoke: ${app}: skipped (${result.reason})`)
continue
}
failures += 1
console.log(`computer-use smoke: ${app}: failed: ${result.error}`)
continue
}
successes += 1
const state = unwrapResult(result.value)
const snapshot = state.snapshot
@@ -86,6 +94,44 @@ for (const app of targets) {
if (failures > 0) {
fail(`${failures} app snapshot smoke check(s) failed`)
}
if (requireTarget && successes === 0) {
fail('no preferred app snapshots succeeded')
}
function runSnapshotSmoke(app) {
const baseArgs = [
'computer',
'get-app-state',
'--session',
session,
'--app',
app,
'--restore-window',
...(includeScreenshot ? [] : ['--no-screenshot']),
'--json'
]
const initial = runCli(baseArgs, { allowFailure: true })
if (initial.ok) {
return initial
}
const error = parseCliFailure(initial.error)
if (error?.code === 'window_not_found') {
return { ok: false, skipped: true, reason: error.message }
}
return initial
}
function parseCliFailure(raw) {
if (!raw) {
return null
}
try {
const parsed = JSON.parse(raw)
return parsed.error ?? null
} catch {
return { code: 'runtime_error', message: String(raw) }
}
}
function valueFlag(name) {
const index = process.argv.indexOf(name)
+190
View File
@@ -0,0 +1,190 @@
import { execFileSync, spawnSync } from 'node:child_process'
import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
const projectDir = path.resolve(import.meta.dirname, '../..')
const smokeScript = path.join(projectDir, 'config', 'scripts', 'computer-use-smoke.mjs')
describe('computer-use smoke script', () => {
it('can launch a runtime before checking apps', () => {
const root = mkdtempSync(path.join(tmpdir(), 'orca-computer-smoke-test-'))
const cliPath = path.join(root, 'fake-cli.cjs')
const callsPath = path.join(root, 'calls.jsonl')
writeFileSync(
cliPath,
[
'const fs = require("node:fs");',
`fs.appendFileSync(${JSON.stringify(callsPath)}, JSON.stringify(process.argv.slice(2)) + "\\n");`,
'const args = process.argv.slice(2);',
'if (args[0] === "open") {',
' console.log(JSON.stringify({ result: { runtime: { state: "ready", runtimeId: "runtime-test" } } }));',
'} else if (args.join(" ") === "computer list-apps --json") {',
' console.log(JSON.stringify({ result: { apps: [] } }));',
'} else {',
' console.error("unexpected args: " + args.join(" "));',
' process.exit(1);',
'}'
].join('\n'),
'utf8'
)
chmodSync(cliPath, 0o755)
const output = execFileSync(process.execPath, [smokeScript, '--launch'], {
encoding: 'utf8',
env: {
...process.env,
ORCA_COMPUTER_SMOKE_CLI_PATH: cliPath,
ORCA_COMPUTER_SMOKE_USER_DATA_PATH: path.join(root, 'user-data')
}
})
expect(output).toContain('computer-use smoke: runtime ready (runtime-test)')
expect(
readFileSync(callsPath, 'utf8')
.trim()
.split('\n')
.map((line) => JSON.parse(line))
).toEqual([
['open', '--json'],
['computer', 'list-apps', '--json']
])
})
it('fails closed when a target app is required but none are available', () => {
const root = mkdtempSync(path.join(tmpdir(), 'orca-computer-smoke-test-'))
const cliPath = writeFakeListAppsCli(root, [])
const result = spawnSync(process.execPath, [smokeScript, '--require-target'], {
encoding: 'utf8',
env: {
...process.env,
ORCA_COMPUTER_SMOKE_CLI_PATH: cliPath,
ORCA_COMPUTER_SMOKE_USER_DATA_PATH: path.join(root, 'user-data'),
ORCA_COMPUTER_SMOKE_APPS: 'TestApp'
}
})
expect(result.status).toBe(1)
expect(result.stderr).toContain('computer-use smoke: no preferred apps are running (TestApp)')
})
it('keeps no-target smoke permissive by default for local probing', () => {
const root = mkdtempSync(path.join(tmpdir(), 'orca-computer-smoke-test-'))
const cliPath = writeFakeListAppsCli(root, [])
const result = spawnSync(process.execPath, [smokeScript], {
encoding: 'utf8',
env: {
...process.env,
ORCA_COMPUTER_SMOKE_CLI_PATH: cliPath,
ORCA_COMPUTER_SMOKE_USER_DATA_PATH: path.join(root, 'user-data'),
ORCA_COMPUTER_SMOKE_APPS: 'TestApp'
}
})
expect(result.status).toBe(0)
expect(result.stdout).toContain('computer-use smoke: no preferred apps are running (TestApp)')
})
it('skips background apps that report window_not_found instead of failing smoke', () => {
const root = mkdtempSync(path.join(tmpdir(), 'orca-computer-smoke-test-'))
const cliPath = writeFakeSnapshotCli(
root,
[
{ name: 'Edge', bundleId: 'com.microsoft.edgemac' },
{ name: 'Notepad', bundleId: null }
],
{
windowNotFoundApps: ['Edge']
}
)
const result = spawnSync(process.execPath, [smokeScript, '--require-target'], {
encoding: 'utf8',
env: {
...process.env,
ORCA_COMPUTER_SMOKE_CLI_PATH: cliPath,
ORCA_COMPUTER_SMOKE_USER_DATA_PATH: path.join(root, 'user-data'),
ORCA_COMPUTER_SMOKE_APPS: 'Edge,Notepad'
}
})
expect(result.status).toBe(0)
expect(result.stdout).toContain('computer-use smoke: Edge: skipped')
expect(result.stdout).toContain('computer-use smoke: Notepad')
})
it('uses cross-platform default app targets for smoke snapshots', () => {
const root = mkdtempSync(path.join(tmpdir(), 'orca-computer-smoke-test-'))
const cliPath = writeFakeSnapshotCli(root, [{ name: 'Notepad', bundleId: null }])
const result = spawnSync(process.execPath, [smokeScript], {
encoding: 'utf8',
env: {
...process.env,
ORCA_COMPUTER_SMOKE_CLI_PATH: cliPath,
ORCA_COMPUTER_SMOKE_USER_DATA_PATH: path.join(root, 'user-data')
}
})
expect(result.status).toBe(0)
expect(result.stdout).toContain('computer-use smoke: Notepad')
})
})
function writeFakeListAppsCli(root, apps) {
const cliPath = path.join(root, 'fake-cli.cjs')
writeFileSync(
cliPath,
[
'const args = process.argv.slice(2);',
'if (args.join(" ") === "computer list-apps --json") {',
` console.log(JSON.stringify({ result: { apps: ${JSON.stringify(apps)} } }));`,
'} else {',
' console.error("unexpected args: " + args.join(" "));',
' process.exit(1);',
'}'
].join('\n'),
'utf8'
)
chmodSync(cliPath, 0o755)
return cliPath
}
function writeFakeSnapshotCli(root, apps, options = {}) {
const cliPath = path.join(root, 'fake-cli.cjs')
writeFileSync(
cliPath,
[
'const args = process.argv.slice(2);',
`const windowNotFoundApps = new Set(${JSON.stringify(options.windowNotFoundApps ?? [])});`,
'if (args.join(" ") === "computer list-apps --json") {',
` console.log(JSON.stringify({ result: { apps: ${JSON.stringify(apps)} } }));`,
'} else if (args[0] === "computer" && args[1] === "get-app-state") {',
' const appIndex = args.indexOf("--app");',
' const app = appIndex >= 0 ? args[appIndex + 1] : "Unknown";',
' if (windowNotFoundApps.has(app)) {',
' console.log(JSON.stringify({ ok: false, error: { code: "window_not_found", message: `app \'${app}\' has no on-screen window` } }));',
' process.exit(1);',
' }',
' console.log(JSON.stringify({ result: {',
' snapshot: {',
' app: { name: app },',
' elementCount: 1,',
' treeText: "[1] text area settable",',
' window: { title: "Untitled" }',
' },',
' screenshot: null',
' } }));',
'} else {',
' console.error("unexpected args: " + args.join(" "));',
' process.exit(1);',
'}'
].join('\n'),
'utf8'
)
chmodSync(cliPath, 0o755)
return cliPath
}
+355 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { spawnSync } from 'node:child_process'
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
@@ -16,7 +16,20 @@ const checks = [
{
name: 'Linux provider Python syntax',
command: 'python3',
args: ['-m', 'py_compile', 'native/computer-use-linux/runtime.py'],
args: [
'-c',
[
'import ast, pathlib',
'source=pathlib.Path("native/computer-use-linux/runtime.py").read_text(encoding="utf-8")',
'ast.parse(source)',
'print("syntax-ok")'
].join(';')
],
enabled: true
},
{
name: 'native provider argument guardrails',
run: verifyNativeArgumentGuardrails,
enabled: true
},
{
@@ -83,6 +96,7 @@ for (const check of checks) {
console.log(`[computer-native] ${check.name}`)
const result = spawnSync(check.command, check.args, {
cwd: repoRoot,
env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1' },
stdio: 'inherit'
})
if (result.status !== 0 || result.error) {
@@ -163,6 +177,345 @@ function verifyWindowsProviderHandshake() {
}
}
function verifyNativeArgumentGuardrails() {
const linux = readFileSync(join(repoRoot, 'native/computer-use-linux/runtime.py'), 'utf8')
const macos = readFileSync(
join(repoRoot, 'native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift'),
'utf8'
)
const windows = readFileSync(join(repoRoot, 'native/computer-use-windows/runtime.ps1'), 'utf8')
const failures = []
if (linux.includes('count or 1') || linux.includes('pages or 1')) {
failures.push('Linux provider must not coerce explicit zero action values to defaults')
}
if (!linux.includes('1 if count is None else count')) {
failures.push('Linux click_count default must only apply when the value is missing')
}
if (!linux.includes('1 if pages is None else pages')) {
failures.push('Linux pages default must only apply when the value is missing')
}
const linuxScrollDefaultPattern = ['str(direction or ', '"down").lower()'].join('')
if (linux.includes(linuxScrollDefaultPattern) || !linux.includes('direction is required')) {
failures.push('Linux scroll direction must be required instead of defaulting to down')
}
if (
!linux.includes('def require_non_empty_string(value, name):') ||
!linux.includes('type_text(require_non_empty_string(operation.get("text"), "text"))') ||
!linux.includes('press_key(require_non_empty_string(operation.get("key"), "key"))')
) {
failures.push(
'Linux text/key actions must reject missing payloads instead of sending empty input'
)
}
if (!linux.includes('"targetById": False')) {
failures.push('Linux provider must not advertise stable window-id targeting')
}
if (
!linux.includes('def parse_positive_pid(value):') ||
!linux.includes('requested_pid is not None and pid_of(app) == requested_pid')
) {
failures.push('Linux pid:N selectors must only match positive process ids')
}
if (!linux.includes('"windowId": None') || !linux.includes('"windowIndex": window_index')) {
failures.push('Linux snapshots must expose AT-SPI child targets as windowIndex, not windowId')
}
if (
!linux.includes(
'def first_descendant(root, predicate, max_nodes=MAX_NODES, max_depth=MAX_DEPTH)'
)
) {
failures.push('Linux focused-element traversal must share the snapshot node/depth budget')
}
if (linux.includes('first_descendant(child, predicate)')) {
failures.push('Linux focused-element traversal must not recurse outside the snapshot budget')
}
if (
linux.includes('return screenshot_payload(best_data, best_width, best_height, original_width)')
) {
failures.push('Linux screenshot payloads must not return oversized best-effort PNGs')
}
if (!linux.includes('write_clipboard("")')) {
failures.push(
'Linux paste_text must clear the temporary clipboard text when no prior value was readable'
)
}
if (!linux.includes('"screenshotError": screenshot.get("error") if screenshot else None')) {
failures.push('Linux size-dropped screenshots must report a structured screenshotError')
}
if (!linux.includes('screenshot exceeded the computer-use payload cap after downscaling')) {
failures.push('Linux screenshot cap failures must explain the size-drop recovery path')
}
if (linux.includes('operation.get("restoreWindow") or has_state')) {
failures.push('Linux keyboard focus checks must verify focus after --restore-window')
}
if (!linux.includes('restoreWindow was requested but the target window is still not focused')) {
failures.push('Linux keyboard focus failures after restore must explain the recovery state')
}
if (!linux.includes('"verification code"') || !linux.includes('return "[redacted]"')) {
failures.push('Linux secure fields must redact verification-code/password-style values')
}
if (!linux.includes('re.search(r"(^|[^a-z0-9])pin([^a-z0-9]|$)", label)')) {
failures.push(
'Linux PIN redaction must match standalone PIN labels without hiding spin buttons'
)
}
if (linux.includes('"password", "passcode", "pin", "secret"')) {
failures.push('Linux secure-field redaction must not treat pin as a raw substring')
}
if (!linux.includes('def restore_window(app, window=None):')) {
failures.push('Linux restore must accept the selected window target')
}
if (!linux.includes('Atspi.Component.grab_focus(component)')) {
failures.push('Linux restore must try AT-SPI focus on the selected window before PID fallback')
}
if (/restore_window\(app\)(?!:)/.test(linux)) {
failures.push('Linux restore call sites must pass the selected window target')
}
if (!linux.includes('even when the click uses an accessibility path')) {
failures.push(
'Linux clicks must activate the target window before accessibility or pointer input'
)
}
if (
!linux.includes('compact_browser_tabs=is_browser_app(query, app)') ||
!linux.includes('inactive browser tabs omitted')
) {
failures.push('Linux browser snapshots must compact large inactive browser tab strips')
}
if (
!linux.includes('record.get("isSelected")') ||
!linux.includes('sanitize_text(record.get("value")) == "1"')
) {
failures.push('Linux browser tab compaction must preserve selected-tab fallbacks')
}
if (!linux.includes('pointer wheel events should land in the requested app window')) {
failures.push(
'Linux synthetic scroll must activate the target window before posting pointer input'
)
}
if (!linux.includes('pointer drags are synthetic global input')) {
failures.push(
'Linux synthetic drag must activate the target window before posting pointer input'
)
}
if (
!linux.includes('"pageup": "Page_Up"') ||
!linux.includes('"pagedown": "Page_Down"') ||
!linux.includes('"insert": "Insert"')
) {
failures.push('Linux key aliases must accept common PageUp/PageDown/Insert names')
}
if (
!macos.includes('private func typeText') ||
!macos.includes('TextInput.replaceSelection(focused.element, with: text)')
) {
failures.push(
'macOS typeText must try verified focused AX text replacement before synthetic keyboard fallback'
)
}
if (!macos.includes('even when the click uses an AX action path')) {
failures.push(
'macOS clicks must activate the target window before accessibility or pointer input'
)
}
if (
!macos.includes('if visibleWindowCount > 0') ||
!macos.includes('ProviderError.coded("permission_denied", "app') ||
!macos.includes('has visible windows but no accessibility window')
) {
failures.push('macOS visible windows without AX access must be reported as permission_denied')
}
if (!macos.includes('"pid:\\(app.pid)"')) {
failures.push(
'macOS snapshot cache must alias follow-up actions by the documented pid:N selector'
)
}
const macOSElementSignature = swiftFunctionBody(macos, 'elementSignature')
if (
macOSElementSignature?.includes('node.value') ||
macOSElementSignature?.includes('node.placeholder')
) {
failures.push(
'macOS element identity must not include mutable text value or placeholder content'
)
}
const macOSCurrentSnapshot = swiftFunctionBody(macos, 'currentSnapshot')
const macOSPruneIndex = macOSCurrentSnapshot?.indexOf('pruneSnapshotCache()') ?? -1
const macOSCachedIndex = macOSCurrentSnapshot?.indexOf('cachedSnapshot(params: params)') ?? -1
if (macOSPruneIndex < 0 || macOSCachedIndex < 0 || macOSPruneIndex > macOSCachedIndex) {
failures.push('macOS cached snapshots must be pruned before cached element lookup')
}
if (
!macos.includes('"pageup": 116') ||
!macos.includes('"pagedown": 121') ||
!macos.includes('"insert": 114')
) {
failures.push('macOS key aliases must accept common PageUp/PageDown/Insert names')
}
if (
!macos.includes('haystack.contains("verification code")') ||
!macos.includes('return "[redacted]"')
) {
failures.push('macOS secure fields must redact verification-code/password-style values')
}
if (windows.includes('if ([bool]$Operation.restoreWindow) { return }')) {
failures.push('Windows keyboard focus checks must verify focus after --restore-window')
}
if (
!windows.includes('function Test-OrcaSensitiveElement') ||
!windows.includes('"verification code"') ||
!windows.includes('if (Test-OrcaSensitiveElement $Element) { return "[redacted]" }')
) {
failures.push(
'Windows secure fields must redact labeled verification-code/password-style values'
)
}
if (
!windows.includes('function Get-OrcaRequiredString($Value, [string]$Name)') ||
!windows.includes('Send-OrcaText $handle (Get-OrcaRequiredString $Operation.text "text")') ||
!windows.includes('Send-OrcaKey $handle (Get-OrcaRequiredString $Operation.key "key")')
) {
failures.push(
'Windows text/key actions must reject missing payloads instead of sending empty input'
)
}
if (!windows.includes('even when UI Automation handles the click')) {
failures.push(
'Windows clicks must activate the target window before UI Automation or pointer input'
)
}
if (
!windows.includes('Render-OrcaTree $root $windowFrame (Test-OrcaBrowserProcess $process)') ||
!windows.includes('inactive browser tabs omitted')
) {
failures.push('Windows browser snapshots must compact large inactive browser tab strips')
}
if (
!windows.includes('[bool]$record.isSelected') ||
!windows.includes('(Format-OrcaSnapshotText $record.value) -eq "1"')
) {
failures.push('Windows browser tab compaction must preserve selected-tab fallbacks')
}
if (!windows.includes('restoreWindow was requested but the target window is still not focused')) {
failures.push('Windows keyboard focus failures after restore must explain the recovery state')
}
const windowFrameFunction = powerShellFunctionBody(windows, 'Get-OrcaWindowFrame')
if (!windowFrameFunction?.includes('$null')) {
failures.push('Windows window-frame fallback must return null when bounds are unavailable')
}
if (windowFrameFunction?.includes('screenshot_failed')) {
failures.push('Windows window-frame fallback must not return screenshot failure objects')
}
const renderedElementIndexFunction = powerShellFunctionBody(
windows,
'Get-OrcaRenderedElementIndex'
)
if (!renderedElementIndexFunction?.includes('$null')) {
failures.push('Windows rendered element index parsing must return null for non-index lines')
}
if (renderedElementIndexFunction?.includes('screenshot_failed')) {
failures.push(
'Windows rendered element index parsing must not return screenshot failure objects'
)
}
if (windows.includes('New-OrcaScreenshotPayload $bestBytes $bestWidth $bestHeight')) {
failures.push('Windows screenshot payloads must not return oversized best-effort PNGs')
}
const boundedScreenshotFunction = powerShellFunctionBody(
windows,
'Get-OrcaBoundedScreenshotPayload'
)
if (!boundedScreenshotFunction?.includes('error = [pscustomobject]')) {
failures.push('Windows screenshot cap failures must return a structured error object')
}
if (
!boundedScreenshotFunction?.includes(
'screenshot exceeded the computer-use payload cap after downscaling'
)
) {
failures.push('Windows screenshot cap failures must explain the size-drop recovery path')
}
if (
!windows.includes(
'screenshotError = if ($null -ne $screenshot) { $screenshot.error } else { $null }'
)
) {
failures.push('Windows size-dropped screenshots must report a structured screenshotError')
}
if (
windows.includes(
'Send-OrcaMouseClick $handle $point.x $point.y $Operation.mouse_button ([int]$Operation.click_count)'
)
) {
failures.push('Windows click_count must be validated before Send-OrcaMouseClick')
}
if (
!windows.includes('$clickCount = Get-OrcaPositiveInteger $Operation.click_count "click_count"')
) {
failures.push('Windows click_count default must be handled by Get-OrcaPositiveInteger')
}
if (
!windows.includes('@("pageup", "page_up")') ||
!windows.includes('@("pagedown", "page_down")') ||
!windows.includes('{ return "{INSERT}" }')
) {
failures.push('Windows key aliases must accept common PageUp/PageDown/Insert names')
}
for (const failure of failures) {
console.error(`[computer-native] ${failure}`)
}
return failures.length === 0
}
function powerShellFunctionBody(source, name) {
const start = source.indexOf(`function ${name}`)
if (start < 0) {
return null
}
const bodyStart = source.indexOf('{', start)
if (bodyStart < 0) {
return null
}
let depth = 0
for (let index = bodyStart; index < source.length; index++) {
const character = source[index]
if (character === '{') {
depth++
} else if (character === '}') {
depth--
if (depth === 0) {
return source.slice(start, index + 1)
}
}
}
return null
}
function swiftFunctionBody(source, name) {
const start = source.indexOf(`func ${name}`)
if (start < 0) {
return null
}
const bodyStart = source.indexOf('{', start)
if (bodyStart < 0) {
return null
}
let depth = 0
for (let index = bodyStart; index < source.length; index++) {
const character = source[index]
if (character === '{') {
depth++
} else if (character === '}') {
depth--
if (depth === 0) {
return source.slice(start, index + 1)
}
}
}
return null
}
function run(command, args) {
if (!hasCommand(command)) {
console.log(`[computer-native] skip ${command}: command not found`)
+288 -61
View File
@@ -45,6 +45,9 @@ BLOCKED_APP_FRAGMENTS = (
"nordpass",
"proton pass",
)
CLIPBOARD_COMMAND_TIMEOUT_SECONDS = 2
CLIPBOARD_OWNER_SETTLE_SECONDS = 0.05
CLIPBOARD_PASTE_SETTLE_SECONDS = 0.15
@dataclass
@@ -142,12 +145,13 @@ def choose_window(app, window_id=None, window_index=None):
windows = windows_for(app)
if not windows:
raise RuntimeError("No top-level AT-SPI window is available for " + name_of(app))
target = window_id if window_id is not None else window_index
if target is not None:
if window_id is not None:
raise RuntimeError("windowId is not supported by the Linux AT-SPI provider; use windowIndex")
if window_index is not None:
for item in windows:
if item[0] == int(target):
if item[0] == int(window_index):
return item
raise RuntimeError(f'windowNotFound("{target}")')
raise RuntimeError(f'windowNotFound("{window_index}")')
for item in windows:
if has_state(item[1], Atspi.StateType.ACTIVE):
return item
@@ -157,7 +161,11 @@ def choose_window(app, window_id=None, window_index=None):
return windows[0]
def restore_window(app):
def restore_window(app, window=None):
target = window if window is not None else app
component = attempt(target.get_component_iface)
if component is not None and attempt(lambda: Atspi.Component.grab_focus(component), False):
return
pid = pid_of(app)
if not pid or not shutil.which("xdotool"):
return
@@ -170,8 +178,17 @@ def restore_window(app):
def require_keyboard_focus(window, operation):
if operation.get("restoreWindow") or has_state(window, Atspi.StateType.ACTIVE):
if has_state(window, Atspi.StateType.ACTIVE):
return
if operation.get("restoreWindow"):
deadline = time.monotonic() + 0.5
while time.monotonic() < deadline:
if has_state(window, Atspi.StateType.ACTIVE):
return
time.sleep(0.05)
if has_state(window, Atspi.StateType.ACTIVE):
return
raise RuntimeError("window_not_focused: keyboard input requires the target window to be focused; restoreWindow was requested but the target window is still not focused; bring it forward manually or check desktop permissions")
raise RuntimeError("window_not_focused: keyboard input requires the target window to be focused; retry with --restore-window")
@@ -180,13 +197,18 @@ def app_matches(app, query):
if not needle:
return False
if needle.startswith("pid:"):
return str(pid_of(app)) == needle[4:]
if needle.isdigit() and pid_of(app) == int(needle):
requested_pid = parse_positive_pid(needle[4:])
return requested_pid is not None and pid_of(app) == requested_pid
if needle.isdigit() and int(needle) > 0 and pid_of(app) == int(needle):
return True
haystacks = [name_of(app).lower()] + [name_of(window).lower() for _, window in windows_for(app)]
return any(value == needle or needle in value for value in haystacks)
def parse_positive_pid(value):
return int(value) if value.isdigit() and int(value) > 0 else None
def find_app(query):
for app in desktop_apps():
if app_matches(app, query):
@@ -262,11 +284,20 @@ def suppress_children(role_key, title, value, summary):
}
def text_iface(node):
return attempt(lambda: node.get_text_iface())
def is_text_node(node):
result = attempt(lambda: node.is_text())
return bool(result) if result is not None else text_iface(node) is not None
def string_value(node):
if is_secure_node(node):
return "[redacted]"
if bool(attempt(node.is_text, False)):
iface = attempt(node.get_text_iface)
if is_text_node(node):
iface = text_iface(node)
count = int(attempt(lambda: Atspi.Text.get_character_count(iface), 0) or 0)
if iface is not None and count > 0:
value = str(attempt(lambda: Atspi.Text.get_text(iface, 0, min(count, TEXT_LIMIT)), "") or "")
@@ -282,7 +313,8 @@ def string_value(node):
def is_secure_node(node):
role = role_of(node).lower()
label = " ".join([role, name_of(node).lower(), accessible_id(node).lower()])
if any(term in label for term in ("password", "passcode", "pin", "secret", "one-time code")):
sensitive_terms = ("password", "passcode", "secret", "one-time code", "verification code")
if any(term in label for term in sensitive_terms) or re.search(r"(^|[^a-z0-9])pin([^a-z0-9]|$)", label):
return True
state_set = attempt(node.get_state_set)
protected_state = getattr(Atspi.StateType, "PROTECTED", None)
@@ -307,13 +339,14 @@ def record(node, index, path, window_rect):
"localizedControlType": role,
"className": str(attempt(node.get_toolkit_name, "") or ""),
"value": string_value(node),
"isSelected": has_state(node, Atspi.StateType.SELECTED),
"nativeWindowHandle": 0,
"frame": rect.to_json() if rect else None,
"actions": action_labels(node),
}
def render_accessibility_tree(root, window_rect, root_path):
def render_accessibility_tree(root, window_rect, root_path, compact_browser_tabs=False):
records = []
lines = []
truncation = {"truncated": False, "maxNodes": MAX_NODES, "maxDepth": MAX_DEPTH, "maxDepthReached": False}
@@ -398,13 +431,95 @@ def render_accessibility_tree(root, window_rect, root_path):
lines.append(("\t" * depth) + line)
if generic_summary or suppress_children(role_key, title, item["value"], generic_summary):
return
child_line_start = len(lines)
for child_index, child in child_items:
walk(child, depth + 1, path + [child_index])
if compact_browser_tabs:
compact_rendered_browser_tabs(records, lines, child_line_start, depth + 1)
walk(root, 0, root_path)
return records, lines, truncation
def compact_rendered_browser_tabs(records, lines, start_line, depth):
tab_line_indexes = [
line_index
for line_index in range(start_line, len(lines))
if is_direct_rendered_browser_tab_line(lines[line_index], depth)
]
if len(tab_line_indexes) < 10:
return
records_by_index = {int(item["index"]): item for item in records}
active_line_indexes = {
line_index
for line_index in tab_line_indexes
if is_active_rendered_browser_tab_line(lines[line_index], depth, records_by_index)
}
if not active_line_indexes:
return
omitted_record_indexes = set()
omitted_count = 0
insertion_index = tab_line_indexes[0]
for line_index in reversed(tab_line_indexes):
if line_index in active_line_indexes:
continue
record_index = rendered_element_index(lines[line_index], depth)
if record_index is not None:
omitted_record_indexes.add(record_index)
del lines[line_index]
omitted_count += 1
if omitted_count <= 0:
return
records[:] = [item for item in records if int(item["index"]) not in omitted_record_indexes]
lines.insert(insertion_index, ("\t" * depth) + f"... {omitted_count} inactive browser tabs omitted")
def is_direct_rendered_browser_tab_line(line, depth):
indent = "\t" * depth
if not line.startswith(indent):
return False
text = line[len(indent):]
if text.startswith("\t"):
return False
return re.match(r"^\d+ (page tab|tab item|tab)($|[ (,])", text, re.IGNORECASE) is not None
def is_active_rendered_browser_tab_line(line, depth, records_by_index):
if "(selected" in line:
return True
record_index = rendered_element_index(line, depth)
record = records_by_index.get(record_index)
if not record:
return False
return bool(record.get("isSelected")) or sanitize_text(record.get("value")) == "1"
def is_browser_app(query, app):
text = f"{query} {name_of(app)}".lower()
tokens = set(re.split(r"[^a-z0-9]+", text))
browser_tokens = {
"arc",
"brave",
"chrome",
"chromium",
"edge",
"msedge",
"firefox",
"librewolf",
"opera",
"vivaldi",
"zen",
}
return not tokens.isdisjoint(browser_tokens)
def rendered_element_index(line, depth):
text = line[len("\t" * depth):]
match = re.match(r"^(\d+)", text)
return int(match.group(1)) if match else None
def capture_png(rect):
if Gdk is None or GdkPixbuf is None or rect is None or os.environ.get("XDG_SESSION_TYPE", "").lower() == "wayland":
return None
@@ -443,14 +558,11 @@ def bounded_png_payload(pixbuf):
# Why: screenshots are sent through JSON/stdout; matching macOS bounds keeps
# large or high-DPI windows from multiplying native, base64, and Node memory.
best_data = data
best_width = original_width
best_height = original_height
scale = min(1.0, MAX_SCREENSHOT_EDGE / max(original_width, original_height))
while scale >= MIN_SCREENSHOT_SCALE:
width = max(1, round(original_width * scale))
height = max(1, round(original_height * scale))
if width == best_width and height == best_height:
if width == original_width and height == original_height:
scale *= SCREENSHOT_SCALE_STEP
continue
scaled = pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)
@@ -461,22 +573,36 @@ def bounded_png_payload(pixbuf):
if candidate is not None:
if len(candidate) <= MAX_SCREENSHOT_PNG_BYTES:
return screenshot_payload(candidate, width, height, original_width)
if len(candidate) < len(best_data):
best_data = candidate
best_width = width
best_height = height
scale *= SCREENSHOT_SCALE_STEP
return screenshot_payload(best_data, best_width, best_height, original_width)
return {
"error": {
"code": "screenshot_failed",
"message": "screenshot exceeded the computer-use payload cap after downscaling; retry with --no-screenshot or target a smaller window",
}
}
def first_descendant(root, predicate):
if predicate(root):
return root
for _, child in children(root):
found = first_descendant(child, predicate)
if found is not None:
return found
def first_descendant(root, predicate, max_nodes=MAX_NODES, max_depth=MAX_DEPTH):
visited_count = 0
stack = [(root, 0)]
seen = set()
while stack and visited_count < max_nodes:
node, depth = stack.pop()
identity = id(node)
if identity in seen:
continue
seen.add(identity)
visited_count += 1
if predicate(node):
return node
if depth >= max_depth:
continue
# Why: focused/selection summaries run after the rendered tree is capped;
# keep them from walking a larger or cyclic AT-SPI tree and timing out.
child_items = list(children(node))
for _, child in reversed(child_items):
stack.append((child, depth + 1))
return None
@@ -488,8 +614,8 @@ def focused_summary(window):
def selected_text(window):
node = first_descendant(window, lambda candidate: has_state(candidate, Atspi.StateType.FOCUSED) and bool(attempt(candidate.is_text, False)))
iface = attempt(node.get_text_iface) if node is not None else None
node = first_descendant(window, lambda candidate: has_state(candidate, Atspi.StateType.FOCUSED) and is_text_node(candidate))
iface = text_iface(node) if node is not None else None
selections = attempt(lambda: Atspi.Text.get_text_selections(iface), [])
if not selections:
return None
@@ -507,7 +633,7 @@ def window_json(app, index, window):
return {
"index": index,
"app": app_json(app),
"id": index,
"id": None,
"title": name_of(window),
"x": round(bounds.x) if bounds else None,
"y": round(bounds.y) if bounds else None,
@@ -522,22 +648,30 @@ def window_json(app, index, window):
def make_snapshot(query, include_screenshot, window_id=None, window_index=None, restore=False):
app = find_app(query)
if restore:
restore_window(app)
window_index, window = choose_window(app, window_id, window_index)
if restore:
restore_window(app, window)
window_index, window = choose_window(app, window_id, window_index)
bounds = screen_rect(window)
records, lines, truncation = render_accessibility_tree(window, bounds, [window_index])
records, lines, truncation = render_accessibility_tree(
window,
bounds,
[window_index],
compact_browser_tabs=is_browser_app(query, app),
)
screenshot = capture_png(bounds) if include_screenshot else None
return {
"snapshotId": str(uuid.uuid4()),
"app": app_json(app),
"windowTitle": name_of(window),
"windowId": window_index,
"windowId": None,
"windowIndex": window_index,
"windowBounds": bounds.to_json() if bounds else None,
"screenshotPngBase64": screenshot["base64"] if screenshot else None,
"screenshotWidth": screenshot["width"] if screenshot else None,
"screenshotHeight": screenshot["height"] if screenshot else None,
"screenshotScale": screenshot["scale"] if screenshot else None,
"screenshotPngBase64": screenshot.get("base64") if screenshot else None,
"screenshotWidth": screenshot.get("width") if screenshot else None,
"screenshotHeight": screenshot.get("height") if screenshot else None,
"screenshotScale": screenshot.get("scale") if screenshot else None,
"screenshotError": screenshot.get("error") if screenshot else None,
"coordinateSpace": "window",
"truncation": truncation,
"treeLines": lines,
@@ -572,7 +706,7 @@ def handshake_response():
"protocolVersion": 1,
"supports": {
"apps": {"list": True, "bundleIds": False, "pids": True},
"windows": {"list": True, "targetById": True, "targetByIndex": True, "focus": False, "moveResize": False},
"windows": {"list": True, "targetById": False, "targetByIndex": True, "focus": False, "moveResize": False},
"observation": {"screenshot": has_screenshot, "annotatedScreenshot": False, "elementFrames": True, "ocr": False},
"actions": {
"click": True,
@@ -662,10 +796,39 @@ def screen_point(window_rect, saved_element=None, x=None, y=None, node=None):
return window_rect.x + float(x), window_rect.y + float(y)
def require_positive_integer(value, name):
try:
parsed = int(value)
except (TypeError, ValueError):
raise RuntimeError(f"{name} must be a positive integer")
if parsed <= 0:
raise RuntimeError(f"{name} must be a positive integer")
return parsed
def require_positive_number(value, name):
try:
parsed = float(value)
except (TypeError, ValueError):
raise RuntimeError(f"{name} must be a positive number")
if not math.isfinite(parsed) or parsed <= 0:
raise RuntimeError(f"{name} must be a positive number")
return parsed
def require_non_empty_string(value, name):
if value is None or str(value) == "":
raise RuntimeError(f"{name} is required")
return str(value)
def click_at(x, y, button, count):
button = (button or "left").lower()
down, up = {"right": ("b3p", "b3r"), "middle": ("b2p", "b2r")}.get(button, ("b1p", "b1r"))
for _ in range(max(1, int(count or 1))):
buttons = {"left": ("b1p", "b1r"), "right": ("b3p", "b3r"), "middle": ("b2p", "b2r")}
if button not in buttons:
raise RuntimeError(f"unsupported mouse button: {button}")
down, up = buttons[button]
for _ in range(require_positive_integer(1 if count is None else count, "click_count")):
Atspi.generate_mouse_event(round(x), round(y), "abs")
Atspi.generate_mouse_event(round(x), round(y), down)
time.sleep(0.03)
@@ -673,13 +836,20 @@ def click_at(x, y, button, count):
def scroll_at(x, y, direction, pages):
down, up = {
if direction is None or str(direction).strip() == "":
raise RuntimeError("direction is required")
direction = str(direction).lower()
wheel_events = {
"up": ("b4p", "b4r"),
"down": ("b5p", "b5r"),
"left": ("b6p", "b6r"),
"right": ("b7p", "b7r"),
}.get(str(direction or "down").lower(), ("b5p", "b5r"))
for _ in range(max(1, math.ceil(float(pages or 1)))):
}
if direction not in wheel_events:
raise RuntimeError(f"unsupported scroll direction: {direction}")
down, up = wheel_events[direction]
page_count = max(1, math.ceil(require_positive_number(1 if pages is None else pages, "pages")))
for _ in range(page_count):
Atspi.generate_mouse_event(round(x), round(y), "abs")
Atspi.generate_mouse_event(round(x), round(y), down)
time.sleep(0.03)
@@ -701,7 +871,8 @@ def key_name(raw):
aliases = {
"return": "Return", "enter": "Return", "tab": "Tab", "escape": "Escape", "esc": "Escape",
"backspace": "BackSpace", "delete": "Delete", "space": "space", "left": "Left", "right": "Right",
"up": "Up", "down": "Down", "page_up": "Page_Up", "page_down": "Page_Down",
"up": "Up", "down": "Down", "home": "Home", "end": "End", "insert": "Insert",
"pageup": "Page_Up", "page_up": "Page_Up", "pagedown": "Page_Down", "page_down": "Page_Down",
}
return aliases.get(str(raw).lower(), str(raw))
@@ -737,25 +908,63 @@ def paste_text(value):
try:
write_clipboard(text)
hotkey("ctrl+v")
# Why: X11 paste consumers may read the selection after the key event
# returns, so keep the pasted text as the owner briefly before restore.
time.sleep(CLIPBOARD_PASTE_SETTLE_SECONDS)
finally:
if previous is not None:
write_clipboard(previous)
else:
# Why: if the clipboard had no readable prior value, do not leave
# the agent-provided paste text in the user's system clipboard.
write_clipboard("")
def read_clipboard():
for command in (["wl-paste"], ["xclip", "-selection", "clipboard", "-o"], ["xsel", "--clipboard", "--output"]):
if shutil.which(command[0]):
result = subprocess.run(command, check=False, capture_output=True, text=True)
try:
result = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
timeout=CLIPBOARD_COMMAND_TIMEOUT_SECONDS,
)
except subprocess.TimeoutExpired:
continue
if result.returncode == 0:
return result.stdout
return None
def write_clipboard(value):
for command in (["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]):
if shutil.which(command[0]):
subprocess.run(command, input=value, check=True, text=True)
return
if shutil.which("wl-copy"):
subprocess.run(
["wl-copy"],
input=value,
check=True,
text=True,
timeout=CLIPBOARD_COMMAND_TIMEOUT_SECONDS,
)
return
for command in (["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]):
if not shutil.which(command[0]):
continue
process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
text=True,
)
if process.stdin is not None:
process.stdin.write(value)
process.stdin.close()
time.sleep(CLIPBOARD_OWNER_SETTLE_SECONDS)
if process.poll() not in (None, 0):
raise RuntimeError(f"{command[0]} failed to set clipboard")
return
raise RuntimeError("paste_text requires wl-copy, xclip, or xsel")
@@ -792,9 +1001,10 @@ def run_operation(operation):
}
app = find_app(operation.get("app", ""))
if operation.get("restoreWindow"):
restore_window(app)
_, window = choose_window(app, operation.get("windowId"), operation.get("windowIndex"))
if operation.get("restoreWindow"):
restore_window(app, window)
_, window = choose_window(app, operation.get("windowId"), operation.get("windowIndex"))
if tool in {"type_text", "press_key", "hotkey", "paste_text"}:
require_keyboard_focus(window, operation)
bounds = screen_rect(window)
@@ -805,11 +1015,22 @@ def run_operation(operation):
action = None
if tool == "click":
# Why: agents expect a click into a target app to make the next
# keyboard action safe, even when the click uses an accessibility path.
restore_window(app, window)
preferred = preferred_action(node)
click_count = int(operation.get("click_count", 1) or 1)
click_count = (
require_positive_integer(operation.get("click_count"), "click_count")
if operation.get("click_count") is not None
else 1
)
handled = operation.get("mouse_button", "left") == "left" and click_count <= 1 and perform_action(node, preferred)
if not handled:
click_at(*screen_point(bounds, saved, operation.get("x"), operation.get("y"), node), operation.get("mouse_button", "left"), operation.get("click_count", 1))
click_at(
*screen_point(bounds, saved, operation.get("x"), operation.get("y"), node),
operation.get("mouse_button", "left"),
click_count,
)
action = {"path": "synthetic", "actionName": None, "fallbackReason": "actionUnsupported"}
else:
labels = action_labels(node)
@@ -823,25 +1044,31 @@ def run_operation(operation):
else:
raise RuntimeError(f'{operation.get("action", "")} is not a valid secondary action')
elif tool == "scroll":
# Why: pointer wheel events should land in the requested app window even
# when another desktop window is currently foregrounded.
restore_window(app, window)
scroll_at(*screen_point(bounds, saved, operation.get("x"), operation.get("y"), node), operation.get("direction"), operation.get("pages"))
action = {"path": "synthetic", "actionName": "scroll", "fallbackReason": None}
elif tool == "drag":
# Why: pointer drags are synthetic global input, so activate the target
# window before using cached coordinates from its accessibility tree.
restore_window(app, window)
drag_between(
screen_point(bounds, operation.get("fromElement"), operation.get("from_x"), operation.get("from_y"), from_node),
screen_point(bounds, operation.get("toElement"), operation.get("to_x"), operation.get("to_y"), to_node),
)
action = {"path": "synthetic", "actionName": "drag", "fallbackReason": None}
elif tool == "type_text":
type_text(operation.get("text", ""))
action = {"path": "synthetic", "actionName": "typeText", "fallbackReason": None}
type_text(require_non_empty_string(operation.get("text"), "text"))
action = {"path": "synthetic", "actionName": "typeText", "fallbackReason": None, "verification": {"state": "unverified", "reason": "synthetic_input"}}
elif tool == "press_key":
press_key(operation.get("key", ""))
action = {"path": "synthetic", "actionName": "pressKey", "fallbackReason": None}
press_key(require_non_empty_string(operation.get("key"), "key"))
action = {"path": "synthetic", "actionName": "pressKey", "fallbackReason": None, "verification": {"state": "unverified", "reason": "synthetic_input"}}
elif tool == "hotkey":
hotkey(operation.get("key", ""))
hotkey(require_non_empty_string(operation.get("key"), "key"))
action = {"path": "synthetic", "actionName": "hotkey", "fallbackReason": None, "verification": {"state": "unverified", "reason": "synthetic_input"}}
elif tool == "paste_text":
paste_text(operation.get("text", ""))
paste_text(require_non_empty_string(operation.get("text"), "text"))
action = {"path": "clipboard", "actionName": "paste", "fallbackReason": None, "verification": {"state": "unverified", "reason": "clipboard_paste"}}
elif tool == "set_value":
if not set_value(node, operation.get("value", "")):
@@ -101,6 +101,30 @@ struct AppDescriptor {
bundleId == "com.microsoft.teams2" ||
bundleId == "notion.id"
}
var isKnownBrowser: Bool {
let bundle = bundleId?.lowercased() ?? ""
let appName = name.lowercased()
return bundle == "com.apple.safari" ||
bundle == "org.mozilla.firefox" ||
bundle == "company.thebrowser.browser" ||
bundle == "app.zen-browser.zen" ||
bundle.hasPrefix("com.google.chrome") ||
bundle.hasPrefix("com.microsoft.edgemac") ||
bundle.hasPrefix("com.brave.browser") ||
bundle.hasPrefix("com.operasoftware.opera") ||
bundle.hasPrefix("com.vivaldi.vivaldi") ||
appName == "safari" ||
appName == "firefox" ||
appName == "arc" ||
appName == "zen" ||
appName.contains("chrome") ||
appName.contains("chromium") ||
appName.contains("edge") ||
appName.contains("brave") ||
appName.contains("opera") ||
appName.contains("vivaldi")
}
}
final class ElementRecord {
@@ -175,8 +199,15 @@ enum ScreenshotStatus {
case failed(String)
}
private struct CachedSnapshotEntry {
let snapshotId: String
let keys: [String]
let createdAt: Date
}
final class Provider {
private var snapshots: [String: Snapshot] = [:]
private var snapshotEntries: [CachedSnapshotEntry] = []
func handle(method: String, params: [String: JSONValue]) throws -> Any {
switch method {
@@ -241,29 +272,97 @@ final class Provider {
windowIndex: windowIndex,
restoreWindow: params["restoreWindow"]?.bool == true
)
let keys = [query, app.name, app.bundleId ?? ""].filter { !$0.isEmpty }.map { $0.lowercased() }
let namespace = snapshotNamespace(params)
// Why: cached snapshots only validate element identity for follow-up
// actions; retaining MB-scale screenshot base64 in the long-lived agent grows memory.
let cachedSnapshot = snapshot.withoutScreenshotPayload()
for key in keys {
if !isExplicitSnapshotNamespace(namespace) {
snapshots[key] = cachedSnapshot
snapshots[snapshotWindowKey(key, snapshot.windowId)] = cachedSnapshot
if let windowIndex {
snapshots[snapshotWindowIndexKey(key, windowIndex)] = cachedSnapshot
}
}
snapshots[namespacedSnapshotKey(namespace, key)] = cachedSnapshot
snapshots[namespacedSnapshotKey(namespace, snapshotWindowKey(key, snapshot.windowId))] = cachedSnapshot
if let windowIndex {
snapshots[namespacedSnapshotKey(namespace, snapshotWindowIndexKey(key, windowIndex))] = cachedSnapshot
}
}
rememberSnapshot(
query: query,
app: app,
snapshot: snapshot.withoutScreenshotPayload(),
params: params,
windowIndex: windowIndex
)
return snapshot
}
private func rememberSnapshot(
query: String,
app: AppDescriptor,
snapshot cachedSnapshot: Snapshot,
params: [String: JSONValue],
windowIndex: Int?
) {
let keys = [query, app.name, app.bundleId ?? "", "pid:\(app.pid)"]
.filter { !$0.isEmpty }
.map { $0.lowercased() }
let namespace = snapshotNamespace(params)
var storedKeys: [String] = []
let canonicalWindowKey = snapshotCanonicalWindowIdKey(cachedSnapshot.windowId)
if !isExplicitSnapshotNamespace(namespace) {
snapshots[canonicalWindowKey.lowercased()] = cachedSnapshot
storedKeys.append(canonicalWindowKey.lowercased())
}
snapshots[namespacedSnapshotKey(namespace, canonicalWindowKey)] = cachedSnapshot
storedKeys.append(namespacedSnapshotKey(namespace, canonicalWindowKey))
if let windowIndex {
let canonicalWindowIndexKey = snapshotCanonicalWindowIndexKey(windowIndex)
if !isExplicitSnapshotNamespace(namespace) {
snapshots[canonicalWindowIndexKey.lowercased()] = cachedSnapshot
storedKeys.append(canonicalWindowIndexKey.lowercased())
}
snapshots[namespacedSnapshotKey(namespace, canonicalWindowIndexKey)] = cachedSnapshot
storedKeys.append(namespacedSnapshotKey(namespace, canonicalWindowIndexKey))
}
for key in keys {
if !isExplicitSnapshotNamespace(namespace) {
snapshots[key] = cachedSnapshot
storedKeys.append(key)
snapshots[snapshotWindowKey(key, cachedSnapshot.windowId)] = cachedSnapshot
storedKeys.append(snapshotWindowKey(key, cachedSnapshot.windowId))
if let windowIndex {
snapshots[snapshotWindowIndexKey(key, windowIndex)] = cachedSnapshot
storedKeys.append(snapshotWindowIndexKey(key, windowIndex))
}
}
snapshots[namespacedSnapshotKey(namespace, key)] = cachedSnapshot
storedKeys.append(namespacedSnapshotKey(namespace, key))
let namespacedWindowKey = namespacedSnapshotKey(
namespace,
snapshotWindowKey(key, cachedSnapshot.windowId)
)
snapshots[namespacedWindowKey] = cachedSnapshot
storedKeys.append(namespacedWindowKey)
if let windowIndex {
let namespacedWindowIndexKey = namespacedSnapshotKey(
namespace,
snapshotWindowIndexKey(key, windowIndex)
)
snapshots[namespacedWindowIndexKey] = cachedSnapshot
storedKeys.append(namespacedWindowIndexKey)
}
}
snapshotEntries.append(
CachedSnapshotEntry(snapshotId: cachedSnapshot.id, keys: storedKeys, createdAt: Date())
)
pruneSnapshotCache()
}
private func pruneSnapshotCache() {
let now = Date()
while let oldest = snapshotEntries.first,
ComputerSnapshotCachePolicy.shouldPrune(
entryCount: snapshotEntries.count,
createdAt: oldest.createdAt,
now: now
) {
let expired = snapshotEntries.removeFirst()
for key in expired.keys where snapshots[key]?.id == expired.snapshotId {
snapshots.removeValue(forKey: key)
}
}
}
private func currentSnapshot(params: [String: JSONValue]) throws -> Snapshot {
pruneSnapshotCache()
let cached = try cachedSnapshot(params: params)
// Why: cached AX frames can be stale after a window move or resize, and
// stale geometry can turn an intended action into a misclick.
@@ -282,14 +381,38 @@ final class Provider {
guard let query = params["app"]?.string, !query.isEmpty else { return nil }
let namespace = snapshotNamespace(params)
if let targetWindowId = try requestedWindowId(params) {
let canonicalKey = snapshotCanonicalWindowIdKey(targetWindowId)
if let cached = snapshots[namespacedSnapshotKey(namespace, canonicalKey)] {
return cached
}
if !isExplicitSnapshotNamespace(namespace), let cached = snapshots[canonicalKey.lowercased()] {
return cached
}
let windowKey = snapshotWindowKey(query.lowercased(), targetWindowId)
return snapshots[namespacedSnapshotKey(namespace, windowKey)] ??
(isExplicitSnapshotNamespace(namespace) ? nil : snapshots[windowKey])
if let cached = snapshots[namespacedSnapshotKey(namespace, windowKey)] {
return cached
}
if !isExplicitSnapshotNamespace(namespace), let cached = snapshots[windowKey] {
return cached
}
return nil
}
if let targetWindowIndex = try requestedWindowIndex(params) {
let canonicalKey = snapshotCanonicalWindowIndexKey(targetWindowIndex)
if let cached = snapshots[namespacedSnapshotKey(namespace, canonicalKey)] {
return cached
}
if !isExplicitSnapshotNamespace(namespace), let cached = snapshots[canonicalKey.lowercased()] {
return cached
}
let windowKey = snapshotWindowIndexKey(query.lowercased(), targetWindowIndex)
return snapshots[namespacedSnapshotKey(namespace, windowKey)] ??
(isExplicitSnapshotNamespace(namespace) ? nil : snapshots[windowKey])
if let cached = snapshots[namespacedSnapshotKey(namespace, windowKey)] {
return cached
}
if !isExplicitSnapshotNamespace(namespace), let cached = snapshots[windowKey] {
return cached
}
return nil
}
let key = query.lowercased()
return snapshots[namespacedSnapshotKey(namespace, key)] ??
@@ -510,7 +633,11 @@ final class Provider {
throw ProviderError.coded("window_not_found", "could not match accessibility window to requested window; run get-app-state again or retry without a window selector")
}
let title = stringAttribute(window, kAXTitleAttribute as String) ?? capture.title ?? app.name
let renderer = TreeRenderer(windowBounds: capture.bounds, focused: focusedElement(appElement: appElement))
let renderer = TreeRenderer(
windowBounds: capture.bounds,
focused: focusedElement(appElement: appElement),
compactBrowserTabs: app.isKnownBrowser
)
renderer.render(window)
let screenshot = includeScreenshot ? capture.screenshotPayload() : nil
let screenshotStatus: ScreenshotStatus = if screenshot != nil {
@@ -601,7 +728,10 @@ final class Provider {
private func click(params: [String: JSONValue]) throws -> [String: Any] {
let snapshot = try currentSnapshot(params: params)
let button = params["mouseButton"]?.string ?? "left"
let count = try optionalInteger(params, "clickCount") ?? 1
let count = try positiveInteger(params["clickCount"]?.number, defaultValue: 1, name: "clickCount")
// Why: agents expect a click into a target app to make the next
// keyboard action safe, even when the click uses an AX action path.
recoverWindow(snapshot.app)
if let elementIndex = try optionalInteger(params, "elementIndex") {
let record = try element(snapshot, elementIndex)
if count <= 1, let actionName = try performClickAction(record: record, mouseButton: button) {
@@ -657,28 +787,45 @@ final class Provider {
private func setValue(params: [String: JSONValue]) throws -> [String: Any] {
let snapshot = try currentSnapshot(params: params)
let record = try element(snapshot, try requiredInteger(params, "elementIndex"))
let expected = try requiredStringAllowingEmpty(params, "value")
guard isSettable(record.element, kAXValueAttribute as String) else {
throw ProviderError.coded("value_not_settable", "element \(record.index) is not settable")
}
let result = AXUIElementSetAttributeValue(record.element, kAXValueAttribute as CFString, try requiredStringAllowingEmpty(params, "value") as CFString)
let result = AXUIElementSetAttributeValue(record.element, kAXValueAttribute as CFString, expected as CFString)
guard result == .success else {
throw ProviderError.coded("accessibility_error", "AXUIElementSetAttributeValue failed with \(result.rawValue)")
}
return actionMetadata(path: "accessibility", actionName: "AXSetValue")
let actual = rawStringAttribute(record.element, kAXValueAttribute as String)
let verification = actual == expected
? verifiedAction(property: "value", expected: expected, actualPreview: actual)
: unverifiedAction(reason: actual == nil ? "provider_unavailable" : "value_mismatch", expected: expected, actualPreview: actual)
return actionMetadata(path: "accessibility", actionName: "AXSetValue", verification: verification)
}
private func typeText(params: [String: JSONValue]) throws -> [String: Any] {
let snapshot = try currentKeyboardSnapshot(params: params)
let text = try requiredString(params, "text")
if let focused = focusedRecord(snapshot), let verification = TextInput.replaceSelection(focused.element, with: text) {
return actionMetadata(path: "accessibility", actionName: "AXReplaceSelection", verification: verification)
}
try requireTargetWindowFocused(snapshot, restoreWindowRequested: params["restoreWindow"]?.bool == true)
try Input.typeText(try requiredString(params, "text"), pid: snapshot.app.pid)
return actionMetadata(path: "synthetic")
try Input.typeText(text, pid: snapshot.app.pid)
return actionMetadata(
path: "synthetic",
actionName: "typeText",
verification: unverifiedAction(reason: "synthetic_input")
)
}
private func pressKey(params: [String: JSONValue]) throws -> [String: Any] {
let snapshot = try currentKeyboardSnapshot(params: params)
try requireTargetWindowFocused(snapshot, restoreWindowRequested: params["restoreWindow"]?.bool == true)
try Input.pressKey(try requiredString(params, "key"), pid: snapshot.app.pid)
return actionMetadata(path: "synthetic")
return actionMetadata(
path: "synthetic",
actionName: "pressKey",
verification: unverifiedAction(reason: "synthetic_input")
)
}
private func hotkey(params: [String: JSONValue]) throws -> [String: Any] {
@@ -717,8 +864,8 @@ final class Provider {
private func scroll(params: [String: JSONValue]) throws -> [String: Any] {
let snapshot = try currentSnapshot(params: params)
let direction = try requiredString(params, "direction")
let pages = params["pages"]?.number ?? 1
let direction = try scrollDirection(try requiredString(params, "direction"))
let pages = try positiveNumber(params["pages"]?.number, defaultValue: 1, name: "pages")
if let elementIndex = try optionalInteger(params, "elementIndex") {
let record = try element(snapshot, elementIndex)
let action = "AXScroll\(direction.capitalized)ByPage"
@@ -825,6 +972,33 @@ private func optionalInteger(_ params: [String: JSONValue], _ key: String) throw
return value
}
private func positiveInteger(_ value: Double?, defaultValue: Int, name: String) throws -> Int {
switch ActionArgumentValidation.positiveInteger(value, defaultValue: defaultValue, name: name) {
case let .success(value):
return value
case let .failure(error):
throw ProviderError.coded("invalid_argument", error.message)
}
}
private func positiveNumber(_ value: Double?, defaultValue: Double, name: String) throws -> Double {
switch ActionArgumentValidation.positiveNumber(value, defaultValue: defaultValue, name: name) {
case let .success(value):
return value
case let .failure(error):
throw ProviderError.coded("invalid_argument", error.message)
}
}
private func scrollDirection(_ value: String) throws -> String {
switch ActionArgumentValidation.scrollDirection(value) {
case let .success(value):
return value
case let .failure(error):
throw ProviderError.coded("invalid_argument", error.message)
}
}
private func parsePid(_ query: String) -> pid_t? {
guard query.hasPrefix("pid:") else { return nil }
guard let pid = Int32(query.dropFirst(4)), pid > 0 else { return nil }
@@ -903,7 +1077,10 @@ private func focusedWindow(appElement: AXUIElement, app: AppDescriptor, visibleW
let permissionHint = visibleWindowCount > 0
? " The app has visible windows, so macOS Accessibility may need Orca Computer Use toggled off and on again in System Settings."
: ""
throw ProviderError.coded("window_not_found", "app '\(app.name)' has no accessibility window; make sure the app has a visible window, then retry with --restore-window.\(permissionHint)")
if visibleWindowCount > 0 {
throw ProviderError.coded("permission_denied", "app '\(app.name)' has visible windows but no accessibility window.\(permissionHint)")
}
throw ProviderError.coded("window_not_found", "app '\(app.name)' has no accessibility window; make sure the app has a visible window, then retry with --restore-window.")
}
private func focusedSystemWindow(systemWide: AXUIElement, app: AppDescriptor) -> AXUIElement? {
@@ -1020,10 +1197,18 @@ private func snapshotWindowKey(_ query: String, _ windowId: CGWindowID) -> Strin
"\(query.lowercased())#window:\(Int(windowId))"
}
private func snapshotCanonicalWindowIdKey(_ windowId: CGWindowID) -> String {
"window-id:\(Int(windowId))"
}
private func snapshotWindowIndexKey(_ query: String, _ windowIndex: Int) -> String {
"\(query.lowercased())#windowIndex:\(windowIndex)"
}
private func snapshotCanonicalWindowIndexKey(_ windowIndex: Int) -> String {
"window-index:\(windowIndex)"
}
private func snapshotNamespace(_ params: [String: JSONValue]) -> String {
if let session = params["session"]?.string, !session.isEmpty {
return "session:\(session)"
@@ -1197,17 +1382,15 @@ private func frame(_ element: AXUIElement, windowBounds: CGRect) -> CGRect? {
}
private func elementSignature(_ node: SnapshotRenderNode) -> String {
// Why: cached element validation should prove identity, not reject text
// controls because their value/placeholder/summary changed after focus.
[
node.role,
node.roleDescription ?? "",
node.title ?? "",
node.label ?? "",
node.linkText ?? "",
node.value ?? "",
node.placeholder ?? "",
node.url ?? "",
node.summary ?? "",
node.rowSummary ?? "",
SnapshotRenderHeuristics.meaningfulActions(node.rawActions, role: node.role).joined(separator: ","),
].joined(separator: "\u{1f}")
}
@@ -1318,6 +1501,7 @@ private func renderScreenshotStatus(_ status: ScreenshotStatus, snapshot: Snapsh
private final class TreeRenderer {
let windowBounds: CGRect
let focused: AXUIElement?
let compactBrowserTabs: Bool
var lines: [String] = []
var records: [Int: ElementRecord] = [:]
var focusedSummary: String?
@@ -1328,9 +1512,10 @@ private final class TreeRenderer {
static let maxNodes = 1200
static let maxDepth = 64
init(windowBounds: CGRect, focused: AXUIElement?) {
init(windowBounds: CGRect, focused: AXUIElement?, compactBrowserTabs: Bool) {
self.windowBounds = windowBounds
self.focused = focused
self.compactBrowserTabs = compactBrowserTabs
}
func render(_ element: AXUIElement, depth: Int = 0, ancestors: [AXUIElement] = []) {
@@ -1413,9 +1598,52 @@ private final class TreeRenderer {
if summary != nil || SnapshotRenderHeuristics.shouldSuppressChildren(node) {
return
}
if compactBrowserTabs, let tabStripCompaction = tabStripCompaction(parent: node, children: children) {
for (childIndex, child) in children.enumerated() where tabStripCompaction.retainedIndexes.contains(childIndex) {
render(child, depth: depth + 1, ancestors: ancestors + [element])
}
lines.append(
String(repeating: "\t", count: depth + 1) +
"... \(tabStripCompaction.omittedCount) inactive browser tabs omitted"
)
return
}
let childLineStart = lines.count
for child in children {
render(child, depth: depth + 1, ancestors: ancestors + [element])
}
if compactBrowserTabs {
compactRenderedBrowserTabs(parent: node, startLine: childLineStart, depth: depth + 1)
}
}
private func compactRenderedBrowserTabs(parent: SnapshotRenderNode, startLine: Int, depth: Int) {
guard SnapshotRenderHeuristics.roleText(parent) == "scroll area" else { return }
let indent = String(repeating: "\t", count: depth)
let tabLineIndexes = lines.indices.dropFirst(startLine).filter { lineIndex in
isDirectRenderedBrowserTabLine(lines[lineIndex], indent: indent)
}
guard tabLineIndexes.count >= 10 else { return }
let activeLineIndexes = Set(tabLineIndexes.filter { lineIndex in
isActiveRenderedBrowserTabLine(lines[lineIndex])
})
guard !activeLineIndexes.isEmpty else { return }
let insertionIndex = tabLineIndexes.first!
var omittedCount = 0
for lineIndex in tabLineIndexes.reversed() where !activeLineIndexes.contains(lineIndex) {
if let recordIndex = renderedElementIndex(lines[lineIndex], indent: indent) {
records.removeValue(forKey: recordIndex)
if focusedElementId == recordIndex {
focusedElementId = nil
focusedSummary = nil
}
}
lines.remove(at: lineIndex)
omittedCount += 1
}
guard omittedCount > 0 else { return }
lines.insert("\(indent)... \(omittedCount) inactive browser tabs omitted", at: insertionIndex)
}
}
@@ -1496,6 +1724,43 @@ private func usesRowsAsPrimaryChildren(role: String) -> Bool {
].contains(role)
}
private func tabStripCompaction(parent: SnapshotRenderNode, children: [AXUIElement]) -> SnapshotTabStripCompaction? {
let childNodes = children.map { child in
let role = stringAttribute(child, kAXRoleAttribute as String) ?? "AXUnknown"
return SnapshotRenderNode(
role: role,
roleDescription: stringAttribute(child, kAXRoleDescriptionAttribute as String),
title: stringAttribute(child, kAXTitleAttribute as String),
label: stringAttribute(child, kAXDescriptionAttribute as String),
value: valueString(child),
traits: traitsFor(child, role: role)
)
}
// Why: browsers expose every open tab through AX; retaining only the active
// tab keeps snapshots focused on the current page instead of stale tab titles.
return SnapshotRenderHeuristics.tabStripCompaction(parent: parent, children: childNodes)
}
private func isDirectRenderedBrowserTabLine(_ line: String, indent: String) -> Bool {
guard line.hasPrefix(indent), !line.dropFirst(indent.count).hasPrefix("\t") else {
return false
}
let text = String(line.dropFirst(indent.count))
return text.range(of: #"^\d+ tab($| \(|,)"#, options: .regularExpression) != nil
}
private func isActiveRenderedBrowserTabLine(_ line: String) -> Bool {
line.contains("(selected") || line.contains("Value: 1")
}
private func renderedElementIndex(_ line: String, indent: String) -> Int? {
let text = line.dropFirst(indent.count)
let digits = text.prefix { character in
character >= "0" && character <= "9"
}
return Int(digits)
}
private func genericTextSummary(
_ element: AXUIElement,
role: String,
@@ -1628,10 +1893,12 @@ private func verifiedAction(property: String, expected: String? = nil, actualPre
]
}
private func unverifiedAction(reason: String) -> [String: Any] {
private func unverifiedAction(reason: String, expected: String? = nil, actualPreview: String? = nil) -> [String: Any] {
[
"state": "unverified",
"reason": reason,
"expected": jsonNullable(expected),
"actualPreview": jsonNullable(actualPreview),
]
}
@@ -2107,7 +2374,8 @@ private enum KeyMap {
"enter": 36, "l": 37, "j": 38, "'": 39, "k": 40, ";": 41, "\\": 42, ",": 43,
"/": 44, "n": 45, "m": 46, ".": 47, "tab": 48, "space": 49, "`": 50,
"backspace": 51, "delete": 51, "escape": 53, "esc": 53, "left": 123, "right": 124,
"down": 125, "up": 126,
"down": 125, "up": 126, "insert": 114, "home": 115, "pageup": 116, "page_up": 116,
"forwarddelete": 117, "end": 119, "pagedown": 121, "page_down": 121,
]
}
@@ -0,0 +1,42 @@
public struct ActionArgumentValidationError: Error, Equatable {
public let message: String
public init(_ message: String) {
self.message = message
}
}
public enum ActionArgumentValidation {
public static func positiveInteger(
_ value: Double?,
defaultValue: Int,
name: String
) -> Result<Int, ActionArgumentValidationError> {
guard let value else { return .success(defaultValue) }
guard value.isFinite, value > 0, let parsed = boundedInteger(value, as: Int.self) else {
return .failure(ActionArgumentValidationError("\(name) must be a positive integer"))
}
return .success(parsed)
}
public static func positiveNumber(
_ value: Double?,
defaultValue: Double,
name: String
) -> Result<Double, ActionArgumentValidationError> {
guard let value else { return .success(defaultValue) }
guard value.isFinite, value > 0 else {
return .failure(ActionArgumentValidationError("\(name) must be a positive number"))
}
return .success(value)
}
public static func scrollDirection(_ value: String) -> Result<String, ActionArgumentValidationError> {
switch value {
case "up", "down", "left", "right":
return .success(value)
default:
return .failure(ActionArgumentValidationError("unsupported scroll direction: \(value)"))
}
}
}
@@ -0,0 +1,14 @@
import Foundation
public enum ComputerSnapshotCachePolicy {
public static let maxEntries = 32
public static let maxAge: TimeInterval = 2 * 60
public static func isExpired(createdAt: Date, now: Date = Date()) -> Bool {
now.timeIntervalSince(createdAt) > maxAge
}
public static func shouldPrune(entryCount: Int, createdAt: Date, now: Date = Date()) -> Bool {
entryCount > maxEntries || isExpired(createdAt: createdAt, now: now)
}
}
@@ -49,6 +49,16 @@ public struct SnapshotRenderNode: Equatable {
}
}
public struct SnapshotTabStripCompaction: Equatable {
public var retainedIndexes: Set<Int>
public var omittedCount: Int
public init(retainedIndexes: Set<Int>, omittedCount: Int) {
self.retainedIndexes = retainedIndexes
self.omittedCount = omittedCount
}
}
public enum SnapshotRenderHeuristics {
public static func displayName(_ node: SnapshotRenderNode) -> String? {
if let title = clean(node.title) {
@@ -124,6 +134,24 @@ public enum SnapshotRenderHeuristics {
shouldSuppressChildren(SnapshotRenderNode(role: role, title: name))
}
public static func tabStripCompaction(
parent: SnapshotRenderNode,
children: [SnapshotRenderNode]
) -> SnapshotTabStripCompaction? {
guard isBrowserTabStripContainer(parent) else { return nil }
let tabIndexes = Set(children.indices.filter { isBrowserTabLike(children[$0]) })
guard tabIndexes.count >= 10 else { return nil }
let selectedTabIndexes = Set(tabIndexes.filter { isSelectedBrowserTab(children[$0]) })
guard !selectedTabIndexes.isEmpty else { return nil }
let nonTabIndexes = Set(children.indices.filter { !tabIndexes.contains($0) })
let retainedIndexes = nonTabIndexes.union(selectedTabIndexes)
let omittedCount = tabIndexes.count - selectedTabIndexes.count
guard omittedCount > 0 else { return nil }
return SnapshotTabStripCompaction(retainedIndexes: retainedIndexes, omittedCount: omittedCount)
}
public static func line(index: Int, node: SnapshotRenderNode) -> String {
let name = displayName(node)
let roleText = roleText(node)
@@ -210,6 +238,26 @@ public enum SnapshotRenderHeuristics {
.replacingOccurrences(of: "]", with: "\\]")
}
private static func isBrowserTabStripContainer(_ node: SnapshotRenderNode) -> Bool {
let roleText = roleText(node)
let title = clean(node.title)?.lowercased() ?? ""
let label = clean(node.label)?.lowercased() ?? ""
let description = clean(node.roleDescription)?.lowercased() ?? ""
return roleText == "scroll area" ||
description == "tab bar" ||
title == "tab bar" ||
label == "tab bar"
}
private static func isBrowserTabLike(_ node: SnapshotRenderNode) -> Bool {
let roleDescription = clean(node.roleDescription)?.lowercased() ?? ""
return node.role == "AXTab" || roleDescription == "tab"
}
private static func isSelectedBrowserTab(_ node: SnapshotRenderNode) -> Bool {
node.traits.contains("selected") || clean(node.value) == "1"
}
private static func splitCamelCase(_ value: String) -> String {
var result = ""
for character in value {
@@ -0,0 +1,71 @@
import OrcaComputerUseMacOSCore
import XCTest
final class ActionArgumentValidationTests: XCTestCase {
func testPositiveIntegerAcceptsPositiveValuesAndDefaults() {
XCTAssertEqual(
try ActionArgumentValidation.positiveInteger(nil, defaultValue: 1, name: "clickCount").get(),
1
)
XCTAssertEqual(
try ActionArgumentValidation.positiveInteger(2, defaultValue: 1, name: "clickCount").get(),
2
)
}
func testPositiveIntegerRejectsZeroNegativeAndNonFiniteValues() {
XCTAssertEqual(
failureMessage(ActionArgumentValidation.positiveInteger(0, defaultValue: 1, name: "clickCount")),
"clickCount must be a positive integer"
)
XCTAssertEqual(
failureMessage(ActionArgumentValidation.positiveInteger(-1, defaultValue: 1, name: "clickCount")),
"clickCount must be a positive integer"
)
XCTAssertEqual(
failureMessage(ActionArgumentValidation.positiveInteger(.infinity, defaultValue: 1, name: "clickCount")),
"clickCount must be a positive integer"
)
}
func testPositiveNumberAcceptsPositiveValuesAndDefaults() {
XCTAssertEqual(
try ActionArgumentValidation.positiveNumber(nil, defaultValue: 1, name: "pages").get(),
1
)
XCTAssertEqual(
try ActionArgumentValidation.positiveNumber(0.5, defaultValue: 1, name: "pages").get(),
0.5
)
}
func testPositiveNumberRejectsZeroNegativeAndNonFiniteValues() {
XCTAssertEqual(
failureMessage(ActionArgumentValidation.positiveNumber(0, defaultValue: 1, name: "pages")),
"pages must be a positive number"
)
XCTAssertEqual(
failureMessage(ActionArgumentValidation.positiveNumber(-0.5, defaultValue: 1, name: "pages")),
"pages must be a positive number"
)
XCTAssertEqual(
failureMessage(ActionArgumentValidation.positiveNumber(.nan, defaultValue: 1, name: "pages")),
"pages must be a positive number"
)
}
func testScrollDirectionRejectsUnknownDirections() {
XCTAssertEqual(try ActionArgumentValidation.scrollDirection("down").get(), "down")
XCTAssertEqual(
failureMessage(ActionArgumentValidation.scrollDirection("diagonal")),
"unsupported scroll direction: diagonal"
)
}
private func failureMessage<T>(_ result: Result<T, ActionArgumentValidationError>) -> String? {
if case let .failure(error) = result {
return error.message
}
return nil
}
}
@@ -0,0 +1,28 @@
import OrcaComputerUseMacOSCore
import XCTest
final class ComputerSnapshotCachePolicyTests: XCTestCase {
func testDoesNotExpireFreshSnapshotsAtTheAgeBoundary() {
let createdAt = Date(timeIntervalSince1970: 100)
let now = createdAt.addingTimeInterval(ComputerSnapshotCachePolicy.maxAge)
XCTAssertFalse(ComputerSnapshotCachePolicy.isExpired(createdAt: createdAt, now: now))
}
func testExpiresSnapshotsOlderThanTheAgeLimit() {
let createdAt = Date(timeIntervalSince1970: 100)
let now = createdAt.addingTimeInterval(ComputerSnapshotCachePolicy.maxAge + 0.001)
XCTAssertTrue(ComputerSnapshotCachePolicy.isExpired(createdAt: createdAt, now: now))
}
func testPrunesWhenCacheExceedsEntryLimit() {
XCTAssertTrue(
ComputerSnapshotCachePolicy.shouldPrune(
entryCount: ComputerSnapshotCachePolicy.maxEntries + 1,
createdAt: Date(),
now: Date()
)
)
}
}
@@ -82,4 +82,89 @@ final class SnapshotRenderingTests: XCTestCase {
XCTAssertEqual(SnapshotRenderHeuristics.line(index: 9, node: node), "9 row General Settings Enabled")
}
func testCompactsLargeBrowserTabStripsToSelectedTab() {
let parent = SnapshotRenderNode(role: "AXScrollArea", roleDescription: "tab bar")
let children = (0..<12).map { index in
SnapshotRenderNode(
role: "AXRadioButton",
roleDescription: "tab",
title: "Tab \(index)",
traits: index == 7 ? ["selected"] : []
)
}
let compaction = SnapshotRenderHeuristics.tabStripCompaction(parent: parent, children: children)
XCTAssertEqual(compaction, SnapshotTabStripCompaction(retainedIndexes: [7], omittedCount: 11))
}
func testInfersLargeBrowserTabStripFromScrollAreaChildren() {
let parent = SnapshotRenderNode(role: "AXScrollArea", roleDescription: "scroll area")
let children = (0..<12).map { index in
SnapshotRenderNode(
role: "AXRadioButton",
roleDescription: "tab",
title: "Tab \(index)",
traits: index == 11 ? ["selected"] : []
)
}
let compaction = SnapshotRenderHeuristics.tabStripCompaction(parent: parent, children: children)
XCTAssertEqual(compaction, SnapshotTabStripCompaction(retainedIndexes: [11], omittedCount: 11))
}
func testUsesOneValueAsSelectedBrowserTabFallback() {
let parent = SnapshotRenderNode(role: "AXScrollArea", roleDescription: "scroll area")
let children = (0..<12).map { index in
SnapshotRenderNode(
role: "AXRadioButton",
roleDescription: "tab",
title: "Tab \(index)",
value: index == 4 ? "1" : "0"
)
}
let compaction = SnapshotRenderHeuristics.tabStripCompaction(parent: parent, children: children)
XCTAssertEqual(compaction, SnapshotTabStripCompaction(retainedIndexes: [4], omittedCount: 11))
}
func testKeepsLargeTabCollectionsWithoutActiveTabExpanded() {
let parent = SnapshotRenderNode(role: "AXGroup")
let children = (0..<12).map { index in
SnapshotRenderNode(role: "AXTab", title: "Tab \(index)", value: "0")
}
XCTAssertNil(SnapshotRenderHeuristics.tabStripCompaction(parent: parent, children: children))
}
func testKeepsLargeNonBrowserTabCollectionsExpanded() {
let parent = SnapshotRenderNode(role: "AXGroup")
let children = (0..<12).map { index in
SnapshotRenderNode(
role: "AXRadioButton",
roleDescription: "tab",
title: "Pane \(index)",
traits: index == 2 ? ["selected"] : []
)
}
XCTAssertNil(SnapshotRenderHeuristics.tabStripCompaction(parent: parent, children: children))
}
func testKeepsSmallTabGroupsExpanded() {
let parent = SnapshotRenderNode(role: "AXTabGroup", roleDescription: "tab group")
let children = (0..<3).map { index in
SnapshotRenderNode(
role: "AXRadioButton",
roleDescription: "tab",
title: "Pane \(index)",
traits: index == 1 ? ["selected"] : []
)
}
XCTAssertNil(SnapshotRenderHeuristics.tabStripCompaction(parent: parent, children: children))
}
}
+218 -38
View File
@@ -172,6 +172,23 @@ function Assert-OrcaProcessAllowed($Process) {
}
}
function Test-OrcaBrowserProcess($Process) {
$name = ([string]$Process.ProcessName).ToLowerInvariant()
$browserProcesses = @(
"arc",
"brave",
"chrome",
"chromium",
"firefox",
"librewolf",
"msedge",
"opera",
"vivaldi",
"zen"
)
$browserProcesses -contains $name
}
function Get-OrcaRootElement($Process) {
if ($Process.MainWindowHandle -eq 0) {
throw "No top-level UI Automation window is available for $($Process.ProcessName)."
@@ -229,9 +246,25 @@ function Restore-OrcaWindow($Process) {
[void][OrcaDesktopWin32]::SetForegroundWindow([IntPtr]$Process.MainWindowHandle)
}
function Test-OrcaWindowFocused([IntPtr]$WindowHandle) {
[OrcaDesktopWin32]::GetForegroundWindow() -eq $WindowHandle
}
function Wait-OrcaWindowFocused([IntPtr]$WindowHandle, [int]$TimeoutMilliseconds) {
$stopwatch = [Diagnostics.Stopwatch]::StartNew()
while ($stopwatch.ElapsedMilliseconds -lt $TimeoutMilliseconds) {
if (Test-OrcaWindowFocused $WindowHandle) { return $true }
Start-Sleep -Milliseconds 50
}
Test-OrcaWindowFocused $WindowHandle
}
function Assert-OrcaKeyboardFocus([IntPtr]$WindowHandle, $Operation) {
if ([bool]$Operation.restoreWindow) { return }
if ([OrcaDesktopWin32]::GetForegroundWindow() -eq $WindowHandle) { return }
if (Test-OrcaWindowFocused $WindowHandle) { return }
if ([bool]$Operation.restoreWindow) {
if (Wait-OrcaWindowFocused $WindowHandle 500) { return }
throw "window_not_focused: keyboard input requires the target window to be focused; restoreWindow was requested but the target window is still not focused; bring it forward manually or check desktop permissions"
}
throw "window_not_focused: keyboard input requires the target window to be focused; retry with --restore-window"
}
@@ -256,9 +289,28 @@ function Get-OrcaRuntimeId($Element) {
try { @($Element.GetRuntimeId()) } catch { @() }
}
function Test-OrcaSensitiveElement($Element) {
try {
if ($Element.Current.IsPassword) { return $true }
} catch {}
$controlType = try { [string]$Element.Current.ControlType.ProgrammaticName } catch { "" }
$parts = @(
(Get-OrcaProperty $Element "LocalizedControlType"),
$controlType,
(Get-OrcaProperty $Element "Name"),
(Get-OrcaProperty $Element "AutomationId"),
(Get-OrcaProperty $Element "ClassName")
)
$haystack = (($parts -join " ") -replace "\s+", " ").ToLowerInvariant()
foreach ($term in @("password", "passcode", "secret", "one-time code", "verification code")) {
if ($haystack.Contains($term)) { return $true }
}
$haystack -match "(^|[^a-z0-9])pin([^a-z0-9]|$)"
}
function Get-OrcaValueText($Element) {
try {
if ($Element.Current.IsPassword) { return "[redacted]" }
if (Test-OrcaSensitiveElement $Element) { return "[redacted]" }
$pattern = $Element.GetCurrentPattern([Windows.Automation.ValuePattern]::Pattern)
$rawValue = $pattern.Current.Value
$text = if ($null -eq $rawValue) { "" } else { [string]$rawValue }
@@ -382,13 +434,23 @@ function New-OrcaElementRecord($Element, [int]$Index, $WindowFrame) {
localizedControlType = Get-OrcaProperty $Element "LocalizedControlType"
className = Get-OrcaProperty $Element "ClassName"
value = Get-OrcaValueText $Element
isSelected = Test-OrcaElementSelected $Element
nativeWindowHandle = $nativeWindowHandle
frame = Get-OrcaElementFrame $Element $WindowFrame
actions = @(Get-OrcaActions $Element)
}
}
function Render-OrcaTree($RootElement, $WindowFrame) {
function Test-OrcaElementSelected($Element) {
try {
$pattern = $Element.GetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern)
return [bool]$pattern.Current.IsSelected
} catch {
return $false
}
}
function Render-OrcaTree($RootElement, $WindowFrame, [bool]$CompactBrowserTabs = $false) {
$records = New-Object System.Collections.Generic.List[object]
$lines = New-Object System.Collections.Generic.List[string]
$seen = New-Object System.Collections.Generic.HashSet[string]
@@ -447,15 +509,84 @@ function Render-OrcaTree($RootElement, $WindowFrame) {
$lines.Add(("`t" * $Depth) + $line)
if (-not [string]::IsNullOrWhiteSpace($genericSummary) -or (Test-OrcaSuppressChildren $roleKey $title $record.value $genericSummary)) { return }
$childLineStart = $lines.Count
for ($i = 0; $i -lt $children.Count; $i++) {
Visit-OrcaNode $children.Item($i) ($Depth + 1)
}
if ($CompactBrowserTabs) {
Compress-OrcaRenderedBrowserTabs $records $lines $childLineStart ($Depth + 1)
}
}
Visit-OrcaNode $RootElement 0
[pscustomobject]@{ elements = @($records.ToArray()); lines = @($lines.ToArray()); truncation = $truncation }
}
function Compress-OrcaRenderedBrowserTabs($Records, $Lines, [int]$StartLine, [int]$Depth) {
$tabLineIndexes = New-Object System.Collections.Generic.List[int]
for ($lineIndex = $StartLine; $lineIndex -lt $Lines.Count; $lineIndex++) {
if (Test-OrcaDirectRenderedBrowserTabLine ([string]$Lines[$lineIndex]) $Depth) {
$tabLineIndexes.Add($lineIndex)
}
}
if ($tabLineIndexes.Count -lt 10) { return }
$recordsByIndex = @{}
foreach ($record in @($Records.ToArray())) {
$recordsByIndex[[int]$record.index] = $record
}
$activeLineIndexes = New-Object System.Collections.Generic.HashSet[int]
foreach ($lineIndex in $tabLineIndexes) {
if (Test-OrcaActiveRenderedBrowserTabLine ([string]$Lines[$lineIndex]) $Depth $recordsByIndex) {
[void]$activeLineIndexes.Add($lineIndex)
}
}
if ($activeLineIndexes.Count -eq 0) { return }
$omittedRecordIndexes = New-Object System.Collections.Generic.HashSet[int]
$omittedCount = 0
$insertionIndex = $tabLineIndexes[0]
for ($i = $tabLineIndexes.Count - 1; $i -ge 0; $i--) {
$lineIndex = $tabLineIndexes[$i]
if ($activeLineIndexes.Contains($lineIndex)) { continue }
$recordIndex = Get-OrcaRenderedElementIndex ([string]$Lines[$lineIndex]) $Depth
if ($null -ne $recordIndex) {
[void]$omittedRecordIndexes.Add([int]$recordIndex)
}
$Lines.RemoveAt($lineIndex)
$omittedCount++
}
if ($omittedCount -le 0) { return }
for ($recordIndex = $Records.Count - 1; $recordIndex -ge 0; $recordIndex--) {
if ($omittedRecordIndexes.Contains([int]$Records[$recordIndex].index)) {
$Records.RemoveAt($recordIndex)
}
}
$Lines.Insert($insertionIndex, (("`t" * $Depth) + "... $omittedCount inactive browser tabs omitted"))
}
function Test-OrcaDirectRenderedBrowserTabLine([string]$Line, [int]$Depth) {
$indent = "`t" * $Depth
if (-not $Line.StartsWith($indent)) { return $false }
$text = $Line.Substring($indent.Length)
if ($text.StartsWith("`t")) { return $false }
$text -match "^\d+ (page tab|tab item|tab)($|[ \(,])"
}
function Test-OrcaActiveRenderedBrowserTabLine([string]$Line, [int]$Depth, $RecordsByIndex) {
if ($Line.Contains("(selected")) { return $true }
$recordIndex = Get-OrcaRenderedElementIndex $Line $Depth
if ($null -eq $recordIndex -or -not $RecordsByIndex.ContainsKey([int]$recordIndex)) { return $false }
$record = $RecordsByIndex[[int]$recordIndex]
[bool]$record.isSelected -or (Format-OrcaSnapshotText $record.value) -eq "1"
}
function Get-OrcaRenderedElementIndex([string]$Line, [int]$Depth) {
$text = $Line.Substring(("`t" * $Depth).Length)
if ($text -match "^(\d+)") { return [int]$Matches[1] }
$null
}
function ConvertTo-OrcaPngBytes([System.Drawing.Image]$Image) {
$stream = $null
try {
@@ -503,14 +634,11 @@ function Get-OrcaBoundedScreenshotPayload([System.Drawing.Bitmap]$Bitmap) {
# Why: screenshots cross process boundaries as PNG base64 in JSON; cap noisy
# large-window payloads to match the macOS provider's memory bounds.
$bestBytes = $pngBytes
$bestWidth = $originalWidth
$bestHeight = $originalHeight
$scale = [Math]::Min(1.0, $MaxScreenshotEdge / [double][Math]::Max($originalWidth, $originalHeight))
while ($scale -ge $MinScreenshotScale) {
$width = [int][Math]::Max(1, [Math]::Round($originalWidth * $scale))
$height = [int][Math]::Max(1, [Math]::Round($originalHeight * $scale))
if ($width -eq $bestWidth -and $height -eq $bestHeight) {
if ($width -eq $originalWidth -and $height -eq $originalHeight) {
$scale *= $ScreenshotScaleStep
continue
}
@@ -522,11 +650,6 @@ function Get-OrcaBoundedScreenshotPayload([System.Drawing.Bitmap]$Bitmap) {
if ($candidateBytes.Length -le $MaxScreenshotPngBytes) {
return New-OrcaScreenshotPayload $candidateBytes $width $height ($width / [double]$originalWidth)
}
if ($candidateBytes.Length -lt $bestBytes.Length) {
$bestBytes = $candidateBytes
$bestWidth = $width
$bestHeight = $height
}
} finally {
if ($null -ne $resized) { $resized.Dispose() }
}
@@ -534,7 +657,12 @@ function Get-OrcaBoundedScreenshotPayload([System.Drawing.Bitmap]$Bitmap) {
$scale *= $ScreenshotScaleStep
}
New-OrcaScreenshotPayload $bestBytes $bestWidth $bestHeight ($bestWidth / [double]$originalWidth)
[pscustomobject]@{
error = [pscustomobject]@{
code = "screenshot_failed"
message = "screenshot exceeded the computer-use payload cap after downscaling; retry with --no-screenshot or target a smaller window"
}
}
}
function Get-OrcaScreenshot([bool]$IncludeScreenshot, $WindowFrame) {
@@ -562,7 +690,7 @@ function New-OrcaSnapshot([string]$Query, [bool]$IncludeScreenshot, $WindowId =
Assert-OrcaWindowTarget $process $WindowId $WindowIndex
$root = Get-OrcaRootElement $process
$windowFrame = Get-OrcaWindowFrame $process $root
$tree = Render-OrcaTree $root $windowFrame
$tree = Render-OrcaTree $root $windowFrame (Test-OrcaBrowserProcess $process)
$screenshot = Get-OrcaScreenshot $IncludeScreenshot $windowFrame
[pscustomobject]@{
@@ -575,6 +703,7 @@ function New-OrcaSnapshot([string]$Query, [bool]$IncludeScreenshot, $WindowId =
screenshotWidth = if ($null -ne $screenshot) { $screenshot.width } else { $null }
screenshotHeight = if ($null -ne $screenshot) { $screenshot.height } else { $null }
screenshotScale = if ($null -ne $screenshot) { $screenshot.scale } else { $null }
screenshotError = if ($null -ne $screenshot) { $screenshot.error } else { $null }
coordinateSpace = "window"
truncation = $tree.truncation
treeLines = @($tree.lines)
@@ -727,13 +856,45 @@ function Set-OrcaElementValue($Element, [string]$Value) {
$false
}
function Get-OrcaRequiredNumber($Value, [string]$Name) {
if ($null -eq $Value) { throw "$Name is required" }
$number = [double]$Value
if ([double]::IsNaN($number) -or [double]::IsInfinity($number)) {
throw "$Name must be a finite number"
}
$number
}
function Get-OrcaPositiveInteger($Value, [string]$Name) {
if ($null -eq $Value) { $Value = 1 }
$number = [int]$Value
if ($number -le 0) { throw "$Name must be a positive integer" }
$number
}
function Get-OrcaPositiveNumber($Value, [string]$Name) {
if ($null -eq $Value) { $Value = 1 }
$number = Get-OrcaRequiredNumber $Value $Name
if ($number -le 0) { throw "$Name must be a positive number" }
$number
}
function Get-OrcaRequiredString($Value, [string]$Name) {
if ($null -eq $Value) { throw "$Name is required" }
$text = [string]$Value
if ($text.Length -eq 0) { throw "$Name is required" }
$text
}
function Get-OrcaScreenPoint($Operation, $WindowFrame) {
if ($null -ne $Operation.element) {
throw "stale element frame; run get-app-state again and use a fresh element index"
}
$x = Get-OrcaRequiredNumber $Operation.x "x"
$y = Get-OrcaRequiredNumber $Operation.y "y"
@{
x = [int][Math]::Round($WindowFrame.x + [double]$Operation.x)
y = [int][Math]::Round($WindowFrame.y + [double]$Operation.y)
x = [int][Math]::Round($WindowFrame.x + $x)
y = [int][Math]::Round($WindowFrame.y + $y)
}
}
@@ -754,17 +915,15 @@ function Get-OrcaElementScreenPoint($Element) {
function Send-OrcaMouseClick([IntPtr]$WindowHandle, [int]$ScreenX, [int]$ScreenY, [string]$Button, [int]$Count) {
[void][OrcaDesktopWin32]::SetForegroundWindow($WindowHandle)
[void][OrcaDesktopWin32]::SetCursorPos($ScreenX, $ScreenY)
$down = $MouseEvents.LeftDown
$up = $MouseEvents.LeftUp
if ($Button -eq "right") {
$down = $MouseEvents.RightDown
$up = $MouseEvents.RightUp
} elseif ($Button -eq "middle") {
$down = $MouseEvents.MiddleDown
$up = $MouseEvents.MiddleUp
$buttonName = if ([string]::IsNullOrWhiteSpace($Button)) { "left" } else { $Button.ToLowerInvariant() }
switch ($buttonName) {
"left" { $down = $MouseEvents.LeftDown; $up = $MouseEvents.LeftUp }
"right" { $down = $MouseEvents.RightDown; $up = $MouseEvents.RightUp }
"middle" { $down = $MouseEvents.MiddleDown; $up = $MouseEvents.MiddleUp }
default { throw "unsupported mouse button: $Button" }
}
for ($i = 0; $i -lt [Math]::Max(1, $Count); $i++) {
for ($i = 0; $i -lt (Get-OrcaPositiveInteger $Count "click_count"); $i++) {
[OrcaDesktopWin32]::mouse_event($down, 0, 0, 0, [UIntPtr]::Zero)
Start-Sleep -Milliseconds 35
[OrcaDesktopWin32]::mouse_event($up, 0, 0, 0, [UIntPtr]::Zero)
@@ -874,6 +1033,9 @@ function ConvertTo-OrcaSendKeysKey([string]$Key) {
"down" { return "{DOWN}" }
"home" { return "{HOME}" }
"end" { return "{END}" }
{ $_ -in @("pageup", "page_up") } { return "{PGUP}" }
{ $_ -in @("pagedown", "page_down") } { return "{PGDN}" }
"insert" { return "{INSERT}" }
default {
if ($Key.Length -eq 1) { return (ConvertTo-OrcaSendKeysText $Key) }
throw "Unsupported key: $Key"
@@ -939,14 +1101,18 @@ function Invoke-OrcaOperation($Operation) {
switch ($Operation.tool) {
"click" {
# Why: agents expect a click into a target app to make the next
# keyboard action safe, even when UI Automation handles the click.
Restore-OrcaWindow $process
$handledByPattern = $false
if ($null -ne $element -and $Operation.mouse_button -ne "right" -and $Operation.mouse_button -ne "middle" -and [int]$Operation.click_count -le 1) {
$clickCount = Get-OrcaPositiveInteger $Operation.click_count "click_count"
if ($null -ne $element -and $Operation.mouse_button -ne "right" -and $Operation.mouse_button -ne "middle" -and $clickCount -le 1) {
$handledByPattern = Invoke-OrcaPrimaryAction $element
}
if (-not $handledByPattern) {
$point = Get-OrcaElementScreenPoint $element
if ($null -eq $point) { $point = Get-OrcaScreenPoint $Operation $windowFrame }
Send-OrcaMouseClick $handle $point.x $point.y $Operation.mouse_button ([int]$Operation.click_count)
Send-OrcaMouseClick $handle $point.x $point.y $Operation.mouse_button $clickCount
$action = [pscustomobject]@{ path = "synthetic"; actionName = $null; fallbackReason = "actionUnsupported" }
} else {
$action = [pscustomobject]@{ path = "accessibility"; actionName = "primaryAction"; fallbackReason = $null }
@@ -960,8 +1126,12 @@ function Invoke-OrcaOperation($Operation) {
$action = [pscustomobject]@{ path = "accessibility"; actionName = $Operation.action; fallbackReason = $null }
}
"scroll" {
$delta = 120 * [int][Math]::Max(1, [Math]::Ceiling([double]$Operation.pages))
if ($Operation.direction -eq "down" -or $Operation.direction -eq "right") { $delta = -1 * $delta }
$delta = 120 * [int][Math]::Ceiling((Get-OrcaPositiveNumber $Operation.pages "pages"))
if ($Operation.direction -eq "down" -or $Operation.direction -eq "right") {
$delta = -1 * $delta
} elseif ($Operation.direction -ne "up" -and $Operation.direction -ne "left") {
throw "unsupported scroll direction: $($Operation.direction)"
}
$point = Get-OrcaElementScreenPoint $element
if ($null -eq $point) { $point = Get-OrcaScreenPoint $Operation $windowFrame }
[void][OrcaDesktopWin32]::SetForegroundWindow($handle)
@@ -972,27 +1142,37 @@ function Invoke-OrcaOperation($Operation) {
"drag" {
$from = Get-OrcaElementScreenPoint $fromElement
if ($null -eq $from -and $null -ne $Operation.fromElement) { throw "stale element frame; run get-app-state again and use a fresh element index" }
if ($null -eq $from) { $from = @{ x = $windowFrame.x + [double]$Operation.from_x; y = $windowFrame.y + [double]$Operation.from_y } }
if ($null -eq $from) {
$from = @{
x = $windowFrame.x + (Get-OrcaRequiredNumber $Operation.from_x "from_x")
y = $windowFrame.y + (Get-OrcaRequiredNumber $Operation.from_y "from_y")
}
}
$to = Get-OrcaElementScreenPoint $toElement
if ($null -eq $to -and $null -ne $Operation.toElement) { throw "stale element frame; run get-app-state again and use a fresh element index" }
if ($null -eq $to) { $to = @{ x = $windowFrame.x + [double]$Operation.to_x; y = $windowFrame.y + [double]$Operation.to_y } }
if ($null -eq $to) {
$to = @{
x = $windowFrame.x + (Get-OrcaRequiredNumber $Operation.to_x "to_x")
y = $windowFrame.y + (Get-OrcaRequiredNumber $Operation.to_y "to_y")
}
}
Send-OrcaDrag $handle $from $to
$action = [pscustomobject]@{ path = "synthetic"; actionName = "drag"; fallbackReason = $null }
}
"type_text" {
Send-OrcaText $handle ([string]$Operation.text)
$action = [pscustomobject]@{ path = "synthetic"; actionName = "typeText"; fallbackReason = $null }
Send-OrcaText $handle (Get-OrcaRequiredString $Operation.text "text")
$action = [pscustomobject]@{ path = "synthetic"; actionName = "typeText"; fallbackReason = $null; verification = [pscustomobject]@{ state = "unverified"; reason = "synthetic_input" } }
}
"press_key" {
Send-OrcaKey $handle ([string]$Operation.key)
$action = [pscustomobject]@{ path = "synthetic"; actionName = "pressKey"; fallbackReason = $null }
Send-OrcaKey $handle (Get-OrcaRequiredString $Operation.key "key")
$action = [pscustomobject]@{ path = "synthetic"; actionName = "pressKey"; fallbackReason = $null; verification = [pscustomobject]@{ state = "unverified"; reason = "synthetic_input" } }
}
"hotkey" {
Send-OrcaHotkey $handle ([string]$Operation.key)
Send-OrcaHotkey $handle (Get-OrcaRequiredString $Operation.key "key")
$action = [pscustomobject]@{ path = "synthetic"; actionName = "hotkey"; fallbackReason = $null; verification = [pscustomobject]@{ state = "unverified"; reason = "synthetic_input" } }
}
"paste_text" {
Send-OrcaPasteText $handle ([string]$Operation.text)
Send-OrcaPasteText $handle (Get-OrcaRequiredString $Operation.text "text")
$action = [pscustomobject]@{ path = "clipboard"; actionName = "paste"; fallbackReason = $null; verification = [pscustomobject]@{ state = "unverified"; reason = "clipboard_paste" } }
}
"set_value" {
+39 -19
View File
@@ -6,19 +6,14 @@ description: >-
desktop app interaction: list apps/windows, get app state, read visible UI,
click controls, type, press keys, scroll, drag, set values, or perform
accessibility actions. Also use for browser windows, webviews, Orca app UI,
or any desktop UI outside Orca's built-in browser. Triggers include "computer
use", "orca computer", "read Spotify", "read Slack", "control/click/read in
a desktop app", and "get app state".
or other desktop UI. Triggers include "computer use", "orca computer", "read
Spotify", "read Slack", "control/click/read in a desktop app", and "get app
state".
---
# Computer Use
Use this skill for desktop UI through Orca's computer-use surface.
Routing:
- Use Orca built-in browser commands (`orca snapshot`, `orca click`, `orca fill`, etc.) only for the browser page embedded inside the Orca app.
- Use `orca computer` for native desktop apps, external browser windows, app/webview chrome, Orca settings/app UI, and any desktop UI outside Orca's embedded browser.
Use this skill for desktop UI through `orca computer`. When the requested target is a website or web app, operate the desktop browser app/window that contains the page.
## Preconditions
@@ -40,7 +35,7 @@ orca computer get-app-state --app com.spotify.client --json
orca computer click --app com.spotify.client --element-index 42 --json
```
Use the fresh state returned by each action for the next element index. Element indexes go stale after navigation, focus changes, scrolling, window changes, or app re-rendering.
Use the fresh state returned by each action for the next element index. Element indexes are the numeric labels shown in the tree; they may be sparse when noisy sections are omitted, so never infer valid indexes from `elementCount` or "Visible elements." Element indexes are short-lived and go stale after delays, navigation, focus changes, scrolling, window changes, or app re-rendering.
## App Selectors
@@ -52,7 +47,7 @@ orca computer get-app-state --app Spotify --json
orca computer get-app-state --app pid:12345 --json
```
For apps with multiple windows or ambiguous titles, run `list-windows` first. Once you choose a window, pass the same `--window-id <id>` or `--window-index <n>` to `get-app-state` and later actions until the target window changes.
For apps with multiple windows or ambiguous titles, run `list-windows` first. Prefer `--window-id <id>` when the listed id is not `none`; otherwise use `--window-index <n>`. Once you choose a window, pass the same selector to `get-app-state` and later actions until the target window changes.
## Commands
@@ -85,21 +80,36 @@ printf '%s' "$TEXT" | orca computer set-value --app <app> --element-index <index
## Action Rules
- Prefer semantic actions: `set-value` for editable fields, `click` for controls, `perform-secondary-action` only for listed action names.
- Use `type-text` only after focusing a field and confirming the app has a focused text receiver.
- Use `press-key` for single/navigation keys such as Return, Escape, Tab, and arrows. Use `hotkey` for shortcuts; prefer `CmdOrCtrl+...` for cross-platform combos.
- After any UI-changing action, use the returned state or rerun `get-app-state` before choosing the next element index.
- Use `type-text` only after focusing a field and confirming the app has a focused text receiver; synthetic keyboard delivery is reported as unverified, so inspect the returned state before assuming text landed.
- Use `press-key` for single/navigation keys such as Return, Escape, Tab, and arrows. Use `hotkey` only for one modifier chord plus one key, such as `CmdOrCtrl+A` or `CmdOrCtrl+Shift+P`; prefer `CmdOrCtrl+...` for cross-platform combos.
- Some actions work in background apps, but this is app-dependent. If success does not change the UI, refresh state and choose a more semantic action or restore/focus the window.
- Prefer `set-value` for text fields that expose values; it can report verified value writes when the provider can read the refreshed value.
- Coordinates are window-local; use coordinates from the latest screenshot/state for the same target window.
## Screenshots
`get-app-state` returns tree+screenshot. Use the tree for indexes/actions and the screenshot for visual confirmation; failed capture usually means hidden, minimized, off-screen, or permission-blocked.
Coordinates passed to `click`, `scroll`, and `drag` are window-local action coordinates. If the screenshot reports `scale` other than `1`, convert visual screenshot pixels before acting:
```text
action_x = screenshot_pixel_x / screenshot.scale
action_y = screenshot_pixel_y / screenshot.scale
```
Prefer element indexes or element frames from the tree when available. Use raw screenshot-derived coordinates only after checking the latest screenshot scale and window size.
On Linux and Windows, screenshots may come from the visible desktop region for the target window bounds. If visual pixels matter, use `--restore-window` so another window does not cover the target region; if you cannot take focus, trust the tree over potentially occluded pixels.
## App Notes
Browsers: for Edge, Chrome, and similar browser windows, set the address/search field directly, then press Return. Do not assume raw typing went to the address bar.
Browsers: for Edge, Chrome, Safari, and similar browser windows, set the address/search field directly, then press Return. Do not assume raw typing went to the address bar. Use `--restore-window` when the browser is not already frontmost. Large tab strips may show only the active tab plus an "inactive browser tabs omitted" marker; treat that as intentional noise reduction and operate on the current page/address bar unless the user asked to manage tabs.
For browser-hosted forms such as Gmail compose, verify the focused UI element after each field action. Page text fields can expose accessibility actions without moving DOM focus; if a click or `set-value` does not change the focused receiver, use `Tab` / `Shift+Tab` from a known focused field or window-local coordinates from a fresh screenshot. Prefer `paste-text` into the verified focused field for draft bodies, then inspect the returned state before continuing.
```bash
orca computer get-app-state --app com.microsoft.edgemac --json
orca computer get-app-state --app com.microsoft.edgemac --restore-window --json
orca computer set-value --app com.microsoft.edgemac --element-index <addressBarIndex> --value "test123" --json
orca computer press-key --app com.microsoft.edgemac --key Return --json
```
@@ -110,12 +120,22 @@ Slack: the accessibility tree may be shallow while the screenshot contains usefu
## Errors
- `app_not_found`: run `list-apps` and retry with the bundle ID.
- `app_not_found`: run `list-apps` and retry with the bundle ID. If the target is a web app such as Gmail, choose the desktop browser app/window that contains it; do not retry `orca computer ... --app Gmail` unchanged because `orca computer` app selectors refer to desktop apps, not website names.
- `app_blocked`: stop; the target is intentionally blocked from computer-use.
- `window_not_found` / `window_stale`: run `list-windows`, choose a current selector, then rerun `get-app-state`.
- `window_not_focused`: retry once with `--restore-window`; if the message says restore was already requested, stop retrying restore and bring the app forward manually or check permissions. For editable fields prefer `set-value`, then inspect before assuming keyboard input worked.
- `element_not_found`: index is stale; run `get-app-state` again.
- `action_failed`: inspect the element role/actions and try a more semantic action.
- `unsupported_capability`: the provider or desktop environment cannot do that action; use a semantic alternative or install the missing dependency if the message names one.
- `action_not_supported`: inspect the element's listed actions and retry with one of those names, or use click/set-value when appropriate.
- `value_not_settable`: the element cannot accept direct value writes; focus it and use keyboard input only when the returned state can be inspected.
- `element_not_clickable`: the element has no actionable frame; use a parent/child element with a frame or choose window-local coordinates from the latest screenshot.
- `invalid_argument`: fix the command flags; do not retry the same command unchanged.
- `action_timeout`: inspect current state before retrying, then use a simpler semantic action or `--no-screenshot` if observation is slow.
- `screenshot_failed`: use `--no-screenshot` if tree state is enough; if the message names Screen Recording or screenshots permission, run `orca computer permissions --id screenshots --json`.
- `accessibility_error`: run `orca computer capabilities --json`; if the message names Accessibility permission, run `orca computer permissions --id accessibility --json`.
- Empty tree or no screenshot: app may have no visible window, be minimized, or need permissions.
- Permission errors: run `orca computer permissions --json`, use the setup UI, then retry.
- Permission errors: run `orca computer permissions --json`, or `orca computer permissions --id accessibility --json` / `--id screenshots --json` when the message names one permission, use the setup UI, then retry.
## Next Action
Confirm Orca status unless already checked, run `orca computer capabilities --json`, then get the target app state with `orca computer get-app-state --app <app> --json`.
Confirm Orca status unless already checked, then run `orca computer capabilities --json`. For website or web-app targets such as Gmail, identify the desktop browser app/window that contains the page, then get that target app state with `orca computer get-app-state --app <app> --json`.
@@ -0,0 +1,9 @@
import { describe, expect, it } from 'vitest'
import { formatBase64PayloadByteCount } from './base64-payload-byte-count'
describe('formatBase64PayloadByteCount', () => {
it('reports decoded binary size for base64 payloads', () => {
const payload = Buffer.from('png-data').toString('base64')
expect(formatBase64PayloadByteCount(payload)).toBe('8 bytes')
})
})
+7
View File
@@ -0,0 +1,7 @@
export function formatBase64PayloadByteCount(base64: string): string {
try {
return `${Buffer.byteLength(base64, 'base64')} bytes`
} catch {
return `${Math.floor((base64.length * 3) / 4)} bytes`
}
}
+78
View File
@@ -0,0 +1,78 @@
import { formatBase64PayloadByteCount } from './base64-payload-byte-count'
import type {
BrowserProfileListResult,
BrowserScreenshotResult,
BrowserSnapshotResult,
BrowserTabCurrentResult,
BrowserTabListResult,
BrowserTabProfileCloneResult,
BrowserTabProfileShowResult,
BrowserTabShowResult
} from '../shared/runtime-types'
export function formatSnapshot(result: BrowserSnapshotResult): string {
const header = `page: ${result.browserPageId}\n${result.title} — ${result.url}\n`
return header + result.snapshot
}
export function formatScreenshot(result: BrowserScreenshotResult): string {
return `Screenshot captured (${result.format}, ${formatBase64PayloadByteCount(result.data)})`
}
export function formatTabList(result: BrowserTabListResult): string {
return formatTabListWithProfiles(result, false)
}
export function formatTabListWithProfiles(
result: BrowserTabListResult,
showProfile: boolean
): string {
if (result.tabs.length === 0) {
return 'No browser tabs open.'
}
return result.tabs
.map((t) => {
const marker = t.active ? '* ' : ' '
const profile = showProfile ? ` [${t.profileLabel ?? t.profileId ?? 'Unknown'}]` : ''
return `${marker}[${t.index}] ${t.browserPageId} ${t.title} — ${t.url}${profile}`
})
.join('\n')
}
export function formatBrowserProfileList(result: BrowserProfileListResult): string {
if (result.profiles.length === 0) {
return 'No browser profiles found.'
}
return result.profiles
.map((profile) => {
const marker = profile.scope === 'default' ? '* ' : ' '
const source = profile.source?.browserFamily ?? 'none'
return `${marker}${profile.id} ${profile.label} ${profile.scope} source:${source}`
})
.join('\n')
}
export function formatTabShow(result: BrowserTabShowResult | BrowserTabCurrentResult): string {
const tab = result.tab
return [
`page: ${tab.browserPageId}`,
`title: ${tab.title}`,
`url: ${tab.url}`,
`active: ${tab.active}`,
`worktree: ${tab.worktreeId ?? 'unknown'}`,
`profile: ${tab.profileLabel ?? tab.profileId ?? 'unknown'}`
].join('\n')
}
export function formatTabProfileShow(result: BrowserTabProfileShowResult): string {
return [
`page: ${result.browserPageId}`,
`worktree: ${result.worktreeId ?? 'unknown'}`,
`profileId: ${result.profileId ?? 'default'}`,
`profile: ${result.profileLabel ?? result.profileId ?? 'default'}`
].join('\n')
}
export function formatTabProfileClone(result: BrowserTabProfileCloneResult): string {
return `Cloned ${result.sourceBrowserPageId} to ${result.browserPageId} (${result.profileLabel ?? result.profileId ?? 'default'})`
}
+317
View File
@@ -0,0 +1,317 @@
import { chmodSync, lstatSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { formatBase64PayloadByteCount } from './base64-payload-byte-count'
import { quoteCliCommandArgument } from './shell-command-quote'
import type {
ComputerActionMetadata,
ComputerActionResult,
ComputerListAppsResult,
ComputerListWindowsResult,
ComputerSnapshotResult
} from '../shared/runtime-types'
import type { RuntimeRpcSuccess } from './runtime-client'
export function formatGetAppState(result: ComputerSnapshotResult): string {
const app = result.snapshot.app
const bundle = app.bundleId ? `, ${app.bundleId}` : ''
const focused =
result.snapshot.focusedElementId === null ? 'none' : `#${result.snapshot.focusedElementId}`
const windowId =
result.snapshot.window.id === null || result.snapshot.window.id === undefined
? ''
: ` id:${result.snapshot.window.id}`
const windowIndex =
result.snapshot.window.index === null || result.snapshot.window.index === undefined
? ''
: ` index:${result.snapshot.window.index}`
const origin =
result.snapshot.window.x === null ||
result.snapshot.window.x === undefined ||
result.snapshot.window.y === null ||
result.snapshot.window.y === undefined
? ''
: ` @ ${result.snapshot.window.x},${result.snapshot.window.y}`
const truncation = result.snapshot.truncation?.truncated
? ` Truncated: yes (max nodes ${result.snapshot.truncation.maxNodes ?? 'unknown'}, max depth ${result.snapshot.truncation.maxDepth ?? 'unknown'})`
: ' Truncated: no'
return [
`${app.name} (pid ${app.pid}${bundle})`,
` Window:${windowId}${windowIndex} "${result.snapshot.window.title}" (${result.snapshot.window.width}x${result.snapshot.window.height}${origin})`,
` Visible elements: ${result.snapshot.elementCount} Focused: ${focused} Coordinates: ${result.snapshot.coordinateSpace}`,
truncation,
` ${formatComputerScreenshotStatus(result)}`,
'',
result.snapshot.treeText
].join('\n')
}
export function prepareComputerCliJsonResult<TResult>(
response: RuntimeRpcSuccess<TResult>
): RuntimeRpcSuccess<TResult> {
const record = response as RuntimeRpcSuccess<TResult> & {
result?: {
screenshot?: { data?: unknown; format?: unknown; path?: unknown } | null
screenshotStatus?: unknown
}
}
if (!record.result || !('screenshotStatus' in record.result)) {
return response
}
const screenshot = record.result?.screenshot
if (!screenshot || typeof screenshot.data !== 'string' || screenshot.data.length === 0) {
return response
}
try {
const extension = screenshot.format === 'png' ? 'png' : 'img'
const outputDir = computerScreenshotTempDir()
cleanupComputerScreenshots(outputDir)
const outputPath = join(outputDir, `${safeCliFileStem(response.id)}-screenshot.${extension}`)
writeFileSync(outputPath, Buffer.from(screenshot.data, 'base64'), { mode: 0o600 })
const expiresAt = new Date(Date.now() + COMPUTER_SCREENSHOT_TTL_MS).toISOString()
return {
...response,
result: {
...record.result,
screenshot: {
...screenshot,
data: undefined,
path: outputPath,
dataOmitted: true,
expiresAt
}
}
} as RuntimeRpcSuccess<TResult>
} catch {
// Why: temp-file export is an ergonomics optimization; keep inline screenshot
// data when disk, permissions, or path validation would otherwise fail --json.
return response
}
}
const COMPUTER_SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000
const COMPUTER_SCREENSHOT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000
const COMPUTER_SCREENSHOT_CLEANUP_MARKER = '.last-cleanup'
function computerScreenshotTempDir(): string {
const outputDir =
process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR || join(tmpdir(), 'orca-computer-use')
mkdirSync(outputDir, { recursive: true, mode: 0o700 })
const stat = lstatSync(outputDir)
if (!stat.isDirectory() || stat.isSymbolicLink()) {
throw new Error(`Unsafe computer screenshot temp path: ${outputDir}`)
}
if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
throw new Error(`Computer screenshot temp path is not owned by the current user: ${outputDir}`)
}
chmodSync(outputDir, 0o700)
return outputDir
}
function cleanupComputerScreenshots(outputDir: string): void {
const now = Date.now()
const markerPath = join(outputDir, COMPUTER_SCREENSHOT_CLEANUP_MARKER)
try {
// Why: agents can call computer-use CLI commands in loops; a marker keeps
// temp cleanup from becoming a synchronous directory scan per screenshot.
if (statSync(markerPath).mtimeMs > now - COMPUTER_SCREENSHOT_CLEANUP_INTERVAL_MS) {
return
}
} catch {
// Missing or unreadable marker means this process should attempt cleanup.
}
const cutoff = now - COMPUTER_SCREENSHOT_TTL_MS
for (const entry of readdirSync(outputDir)) {
if (!entry.endsWith('-screenshot.png') && !entry.endsWith('-screenshot.img')) {
continue
}
const path = join(outputDir, entry)
try {
if (statSync(path).mtimeMs < cutoff) {
rmSync(path, { force: true })
}
} catch {
// Best-effort cleanup only; formatting should not fail because a temp file raced.
}
}
try {
writeFileSync(markerPath, `${now}\n`, { mode: 0o600 })
} catch {
// Best-effort marker only; stale cleanup state should not hide a screenshot.
}
}
function safeCliFileStem(value: string): string {
return value.replaceAll(/[^a-zA-Z0-9._-]/g, '_')
}
export function formatListApps(result: ComputerListAppsResult): string {
if (result.apps.length === 0) {
return 'No apps found.'
}
return result.apps
.map((app) => {
const bundle = app.bundleId ? ` ${app.bundleId}` : ''
return `${app.name} pid:${app.pid}${bundle}`
})
.join('\n')
}
export function formatListWindows(result: ComputerListWindowsResult): string {
if (result.windows.length === 0) {
return `No windows found for ${result.app.name}.`
}
return result.windows
.map((window) => {
const id = window.id === null || window.id === undefined ? 'none' : String(window.id)
const origin =
window.x === null || window.x === undefined || window.y === null || window.y === undefined
? ''
: ` @ ${window.x},${window.y}`
const screen =
window.screenIndex === null || window.screenIndex === undefined
? ''
: ` screen:${window.screenIndex}`
const state = [
window.isMinimized ? 'minimized' : null,
window.isOffscreen ? 'offscreen' : null
].filter(Boolean)
const stateText = state.length > 0 ? ` ${state.join(',')}` : ''
return `[${window.index}] id:${id} "${window.title}" (${window.width}x${window.height}${origin})${screen}${stateText}`
})
.join('\n')
}
export type ComputerActionFollowUpTarget = {
session?: string
worktree?: string
windowId?: number
windowIndex?: number
restoreWindow?: boolean
}
export function formatComputerAction(
verb: string,
result: ComputerActionResult,
target: ComputerActionFollowUpTarget = {}
): string {
const path = result.action?.path ? ` via ${result.action.path}` : ''
const verification = formatActionVerification(result.action)
const followUpCommand = formatComputerFollowUpCommand(result, target)
const unverified = isUnverifiedComputerAction(result.action)
const outcome = unverified ? 'attempted' : 'completed'
const screenshotFailure = formatComputerActionScreenshotFailure(result)
const inspectTail = unverified
? 'Inspect with the command above or use the --json result before assuming it worked.'
: 'Use the --json result or rerun state before choosing the next element index.'
return `${formatActionVerb(verb)} ${outcome}${path}${verification}; ${result.snapshot.elementCount} visible elements in current window.${screenshotFailure} Use \`${followUpCommand}\` to inspect. ${inspectTail}`
}
function formatComputerFollowUpCommand(
result: ComputerActionResult,
target: ComputerActionFollowUpTarget
): string {
const args = [
'orca',
'computer',
'get-app-state',
'--app',
quoteCliCommandArgument(result.snapshot.app.bundleId ?? result.snapshot.app.name)
]
if (target.session) {
args.push('--session', quoteCliCommandArgument(target.session))
} else if (target.worktree) {
args.push('--worktree', quoteCliCommandArgument(target.worktree))
}
const windowChanged =
result.action?.verification?.state === 'unverified' &&
result.action.verification.reason === 'window_changed'
if (!windowChanged && target.windowId !== undefined) {
args.push('--window-id', String(target.windowId))
} else if (!windowChanged && target.windowIndex !== undefined) {
args.push('--window-index', String(target.windowIndex))
} else {
const windowId = result.action?.targetWindowId ?? result.snapshot.window.id
const windowIndex = result.action?.targetWindowIndex ?? result.snapshot.window.index
if (windowId !== null && windowId !== undefined) {
args.push('--window-id', String(windowId))
} else if (windowIndex !== null && windowIndex !== undefined) {
args.push('--window-index', String(windowIndex))
}
}
if (target.restoreWindow) {
args.push('--restore-window')
}
return args.join(' ')
}
function formatActionVerification(action: ComputerActionMetadata | undefined): string {
const verification = action?.verification
if (!verification) {
if (action?.path === 'synthetic') {
return ', unverified (synthetic input)'
}
if (action?.path === 'clipboard') {
return ', unverified (clipboard paste)'
}
return ''
}
if (verification.state === 'verified') {
return `, verified ${verification.property}`
}
return `, unverified (${verification.reason.replaceAll('_', ' ')})`
}
function isUnverifiedComputerAction(action: ComputerActionMetadata | undefined): boolean {
if (action?.verification) {
return action.verification.state === 'unverified'
}
return action?.path === 'synthetic' || action?.path === 'clipboard'
}
function formatComputerActionScreenshotFailure(result: ComputerActionResult): string {
if (result.screenshotStatus.state !== 'failed') {
return ''
}
return ` Screenshot failed (${result.screenshotStatus.code}): ${result.screenshotStatus.message}.`
}
function formatComputerScreenshotStatus(result: ComputerSnapshotResult): string {
if (result.screenshotStatus.state === 'captured' && result.screenshot) {
const bytes = result.screenshot.data
? formatBase64PayloadByteCount(result.screenshot.data)
: `saved to ${result.screenshot.path ?? 'temporary file'}`
const dimensions = `${result.screenshot.width}x${result.screenshot.height}`
const scale = result.screenshot.scale
const scaleDetail =
Number.isFinite(scale) && scale > 0 && scale !== 1
? `, scale ${formatComputerScreenshotScale(scale)}; coordinate x/y = screenshot pixels / ${formatComputerScreenshotScale(scale)}`
: ''
const engine = result.screenshotStatus.metadata?.engine
const detail = engine
? `${result.screenshot.format}, ${bytes}, ${dimensions}${scaleDetail}, ${engine}`
: `${result.screenshot.format}, ${bytes}, ${dimensions}${scaleDetail}`
return `Screenshot captured (${detail})`
}
if (result.screenshotStatus.state === 'skipped') {
return 'Screenshot skipped (--no-screenshot)'
}
if (result.screenshotStatus.state === 'failed') {
return `Screenshot failed (${result.screenshotStatus.code}): ${result.screenshotStatus.message}`
}
return 'Screenshot was not captured'
}
function formatComputerScreenshotScale(scale: number): string {
return Number.isInteger(scale)
? String(scale)
: scale.toFixed(3).replace(/0+$/u, '').replace(/\.$/u, '')
}
function formatActionVerb(verb: string): string {
return verb
.split('-')
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ')
}
+319 -3
View File
@@ -2,10 +2,12 @@ import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { quoteCliCommandArgument } from './shell-command-quote'
import { RuntimeRpcFailureError } from './runtime-client'
import {
formatCliError,
formatComputerAction,
formatGetAppState,
formatTerminalRead,
formatWorktreeList,
printResult
@@ -57,6 +59,34 @@ function worktree(overrides: Partial<RuntimeWorktreeRecord> = {}): RuntimeWorktr
}
describe('formatCliError', () => {
it('prints structured computer-use startup recovery steps', () => {
const error = new RuntimeRpcFailureError({
id: 'req_1',
ok: false,
error: {
code: 'app_not_found',
message: 'app not found: Gmail',
data: {
nextSteps: [
'Run `orca computer list-apps --json` and retry with the exact app name or bundle ID.',
'If the target is a website or web app such as Gmail, choose the desktop browser app/window that contains it; `orca computer` app selectors refer to desktop apps, not website names.',
'Do not retry the same `orca computer ... --app <web app>` command unchanged.',
'If the desired browser is not listed, open or focus that browser first, then retry `orca computer list-apps --json` and `orca computer list-windows --app <browser> --json`.'
]
}
},
_meta: { runtimeId: 'runtime-1' }
})
const output = formatCliError(error)
expect(output).toContain('app not found: Gmail')
expect(output).toContain('Next step: Run `orca computer list-apps --json`')
expect(output).toContain('desktop browser app/window')
expect(output).toContain('--app <web app>')
expect(output).not.toContain('orca goto')
})
it('prints runtime next steps for structured lineage errors', () => {
const error = new RuntimeRpcFailureError({
id: 'req_1',
@@ -221,7 +251,11 @@ describe('formatComputerAction', () => {
})
expect(output).toContain(
"Use `orca computer get-app-state --app 'Text Editor' --worktree id:repo::/tmp/repo --window-id 99`"
`Use \`orca computer get-app-state --app ${quoteCliCommandArgument('Text Editor')} --worktree id:repo::/tmp/repo --window-id 99\``
)
expect(output).toContain('5 visible elements in current window')
expect(output).toContain(
'Use the --json result or rerun state before choosing the next element index.'
)
})
@@ -249,9 +283,226 @@ describe('formatComputerAction', () => {
'Use `orca computer get-app-state --app com.apple.finder --session manual --window-index 1`'
)
})
it('surfaces action screenshot failures in pretty output', () => {
const result: ComputerActionResult = {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Document', id: 42, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 5,
focusedElementId: null
},
screenshot: null,
screenshotStatus: {
state: 'failed',
code: 'screenshot_failed',
message:
'screenshot exceeded the computer-use payload cap after downscaling; retry with --no-screenshot or target a smaller window'
},
action: {
path: 'synthetic',
targetWindowId: 42
}
}
const output = formatComputerAction('click', result)
expect(output).toContain('Click attempted via synthetic, unverified (synthetic input)')
expect(output).toContain('Screenshot failed (screenshot_failed)')
expect(output).toContain('payload cap')
expect(output).toContain(
'Use `orca computer get-app-state --app com.apple.finder --window-id 42`'
)
expect(output).not.toContain('Click completed')
})
it('does not treat clipboard actions without verification as completed', () => {
const result: ComputerActionResult = {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', id: 42, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 5,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'clipboard',
actionName: 'paste',
targetWindowId: 42
}
}
const output = formatComputerAction('paste-text', result)
expect(output).toContain('Paste Text attempted via clipboard, unverified (clipboard paste)')
expect(output).toContain('Inspect with the command above')
expect(output).not.toContain('Paste Text completed')
})
it('respects explicit verification metadata on synthetic action results', () => {
const result: ComputerActionResult = {
snapshot: {
id: 'snap-1',
app: { name: 'Automation Harness', bundleId: null, pid: 100 },
window: { title: 'Harness', id: 42, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 5,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'synthetic',
actionName: 'typeText',
targetWindowId: 42,
verification: {
state: 'verified',
property: 'focusedText',
expected: 'draft body',
actualPreview: 'draft body'
}
}
}
const output = formatComputerAction('type-text', result)
expect(output).toContain('Type Text completed via synthetic, verified focusedText')
expect(output).not.toContain('Type Text attempted')
expect(output).not.toContain('unverified (synthetic input)')
})
it('drops stale requested window selectors after a window-changed fallback', () => {
const result: ComputerActionResult = {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Replacement', id: 42, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 5,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'synthetic',
targetWindowId: 42,
verification: { state: 'unverified', reason: 'window_changed' }
}
}
const output = formatComputerAction('click', result, {
session: 'manual',
windowIndex: 1
})
expect(output).toContain(
'Use `orca computer get-app-state --app com.apple.finder --session manual --window-id 42`'
)
expect(output).toContain('Click attempted via synthetic, unverified (window changed)')
expect(output).toContain(
'Inspect with the command above or use the --json result before assuming it worked.'
)
expect(output).not.toContain('Click completed')
expect(output).not.toContain('--window-index 1')
})
it('uses snapshot window index for follow-up commands when the provider has no stable window id', () => {
const result: ComputerActionResult = {
snapshot: {
id: 'snap-1',
app: { name: 'Linux Browser', bundleId: null, pid: 100 },
window: { title: 'Inbox', id: null, index: 2, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 5,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'synthetic',
targetWindowId: null
}
}
const output = formatComputerAction('click', result)
expect(output).toContain(
`Use \`orca computer get-app-state --app ${quoteCliCommandArgument('Linux Browser')} --window-index 2\``
)
expect(output).not.toContain('--window-id')
})
it('uses action target window index before snapshot fallback for ID-less providers', () => {
const result: ComputerActionResult = {
snapshot: {
id: 'snap-1',
app: { name: 'Linux Browser', bundleId: null, pid: 100 },
window: { title: 'Inbox', id: null, index: 4, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 5,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'synthetic',
targetWindowId: null,
targetWindowIndex: 2
}
}
const output = formatComputerAction('click', result)
expect(output).toContain(
`Use \`orca computer get-app-state --app ${quoteCliCommandArgument('Linux Browser')} --window-index 2\``
)
expect(output).not.toContain('--window-index 4')
expect(output).not.toContain('--window-id')
})
})
describe('printResult computer screenshots', () => {
it('shows screenshot dimensions and coordinate scale in pretty state output', () => {
const output = formatGetAppState({
snapshot: {
id: 'snap-test',
app: { name: 'Editor', bundleId: null, pid: 123 },
window: { title: 'Editor', id: null, index: 2, width: 1200, height: 800 },
coordinateSpace: 'window',
treeText: 'App=Editor (pid 123)',
elementCount: 1,
focusedElementId: null,
truncation: { truncated: false }
},
screenshot: {
data: Buffer.from('png-data').toString('base64'),
format: 'png',
width: 600,
height: 400,
scale: 0.5
},
screenshotStatus: { state: 'captured' }
})
expect(output).toContain('Screenshot captured (png')
expect(output).toContain('600x400')
expect(output).toContain('coordinate x/y = screenshot pixels / 0.5')
expect(output).toContain('Window: index:2 "Editor"')
expect(output).toContain('Visible elements: 1')
expect(output).not.toContain('Elements: 1')
})
it('removes expired screenshot temp files when cleanup is due', () => {
testScreenshotDir = mkdtempSync(join(tmpdir(), 'orca-format-test-'))
process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR = testScreenshotDir
@@ -272,7 +523,8 @@ describe('printResult computer screenshots', () => {
width: 1,
height: 1,
scale: 1
}
},
screenshotStatus: { state: 'captured' }
},
_meta: { runtimeId: 'runtime-1' }
},
@@ -306,7 +558,8 @@ describe('printResult computer screenshots', () => {
width: 1,
height: 1,
scale: 1
}
},
screenshotStatus: { state: 'captured' }
},
_meta: { runtimeId: 'runtime-1' }
},
@@ -321,4 +574,67 @@ describe('printResult computer screenshots', () => {
expect(output.result.screenshot.dataOmitted).toBe(true)
expect(output.result.screenshot.path).toContain('req_1-screenshot.png')
})
it('keeps inline screenshot data when temp export fails', () => {
testScreenshotDir = join(tmpdir(), `orca-format-blocked-${Date.now()}`)
writeFileSync(testScreenshotDir, 'not-a-directory')
process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR = testScreenshotDir
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined)
const screenshotData = Buffer.from('png-data').toString('base64')
printResult(
{
id: 'req-export-fail',
ok: true,
result: {
screenshot: {
data: screenshotData,
format: 'png',
width: 1,
height: 1,
scale: 1
},
screenshotStatus: { state: 'captured' }
},
_meta: { runtimeId: 'runtime-1' }
},
true,
() => 'unused'
)
const output = JSON.parse(logSpy.mock.calls[0][0]) as {
result: { screenshot: { data: string; path?: string; dataOmitted?: boolean } }
}
expect(output.result.screenshot.data).toBe(screenshotData)
expect(output.result.screenshot.path).toBeUndefined()
expect(output.result.screenshot.dataOmitted).toBeUndefined()
})
it('does not rewrite non-computer nested screenshot JSON payloads', () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined)
const screenshotData = Buffer.from('png-data').toString('base64')
printResult(
{
id: 'req-browser-like',
ok: true,
result: {
screenshot: {
data: screenshotData,
format: 'png'
}
},
_meta: { runtimeId: 'runtime-1' }
},
true,
() => 'unused'
)
const output = JSON.parse(logSpy.mock.calls[0][0]) as {
result: { screenshot: { data: string; path?: string; dataOmitted?: boolean } }
}
expect(output.result.screenshot.data).toBe(screenshotData)
expect(output.result.screenshot.path).toBeUndefined()
expect(output.result.screenshot.dataOmitted).toBeUndefined()
})
})
+89 -717
View File
@@ -1,63 +1,87 @@
/* eslint-disable max-lines -- Why: CLI result formatters are centralized so handlers can stay thin RPC glue. */
import { chmodSync, lstatSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import type {
BrowserProfileListResult,
BrowserTabCurrentResult,
BrowserScreenshotResult,
BrowserSnapshotResult,
BrowserTabListResult,
BrowserTabProfileCloneResult,
BrowserTabProfileShowResult,
BrowserTabShowResult,
ComputerActionResult,
ComputerActionVerification,
ComputerListAppsResult,
ComputerListWindowsResult,
ComputerSnapshotResult,
CliStatusResult,
RuntimeRepoList,
RuntimeRepoSearchRefs,
RuntimeTerminalClose,
RuntimeTerminalCreate,
RuntimeTerminalFocus,
RuntimeTerminalListResult,
RuntimeTerminalRead,
RuntimeTerminalRename,
RuntimeTerminalSend,
RuntimeTerminalShow,
RuntimeTerminalSplit,
RuntimeTerminalWait,
RuntimeWorktreeListResult,
RuntimeWorktreePsResult,
RuntimeWorktreeRecord
} from '../shared/runtime-types'
import type { Automation, AutomationRun } from '../shared/automations-types'
import { formatAutomationPrecheckTimeout } from '../shared/automation-precheck'
import { formatAutomationSchedule } from '../shared/automation-schedules'
import type { PublicKnownRuntimeEnvironment } from '../shared/runtime-environments'
import type { MemorySnapshot, WorktreeMemory } from '../shared/types'
import type { CliStatusResult } from '../shared/runtime-types'
import { computerUseErrorRecoveryData } from '../shared/computer-use-error-recovery'
import { prepareComputerCliJsonResult } from './computer-format'
import type { RuntimeRpcFailure, RuntimeRpcSuccess } from './runtime-client'
import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client'
export {
formatBrowserProfileList,
formatScreenshot,
formatSnapshot,
formatTabList,
formatTabListWithProfiles,
formatTabProfileClone,
formatTabProfileShow,
formatTabShow
} from './browser-format'
export {
formatComputerAction,
formatGetAppState,
formatListApps,
formatListWindows
} from './computer-format'
export type { ComputerActionFollowUpTarget } from './computer-format'
export {
formatTerminalClose,
formatTerminalCreate,
formatTerminalFocus,
formatTerminalList,
formatTerminalRead,
formatTerminalRename,
formatTerminalSend,
formatTerminalShow,
formatTerminalSplit,
formatTerminalWait
} from './terminal-format'
export {
formatAutomationList,
formatAutomationRemoved,
formatAutomationRun,
formatAutomationRuns,
formatAutomationShow,
formatEnvironment,
formatEnvironmentList,
formatMemorySnapshot,
formatRepoList,
formatRepoRefs,
formatRepoShow,
formatWorktreeList,
formatWorktreePs,
formatWorktreeShow
} from './workspace-format'
type CliErrorContext = {
commandPath?: readonly string[]
}
export function printResult<TResult>(
response: RuntimeRpcSuccess<TResult>,
json: boolean,
formatter: (value: TResult) => string
): void {
if (json) {
console.log(JSON.stringify(prepareCliJsonResult(response), null, 2))
console.log(JSON.stringify(prepareComputerCliJsonResult(response), null, 2))
return
}
console.log(formatter(response.result))
}
export function formatCliError(error: unknown): string {
export function formatCliError(error: unknown, context: CliErrorContext = {}): string {
const message = error instanceof Error ? error.message : String(error)
if (error instanceof RuntimeClientError && error.code === 'runtime_unavailable') {
return `${message}\nOrca is not running. Run 'orca open' first.`
}
if (
error instanceof RuntimeClientError &&
error.code === 'invalid_argument' &&
context.commandPath?.[0] === 'computer'
) {
return formatMessageWithNextSteps(
message,
computerUseErrorRecoveryData('invalid_argument')?.nextSteps ?? []
)
}
if (
error instanceof RuntimeRpcFailureError &&
error.response.error.code === 'runtime_unavailable'
@@ -72,14 +96,12 @@ export function formatCliError(error: unknown): string {
(step): step is string => typeof step === 'string'
)
: []
if (nextSteps.length > 0) {
return `${message}\n${nextSteps.map((step) => `Next step: ${step}`).join('\n')}`
}
return formatMessageWithNextSteps(message, nextSteps)
}
return message
}
export function reportCliError(error: unknown, json: boolean): void {
export function reportCliError(error: unknown, json: boolean, context: CliErrorContext = {}): void {
if (json) {
if (error instanceof RuntimeRpcFailureError) {
console.log(JSON.stringify(error.response, null, 2))
@@ -89,7 +111,8 @@ export function reportCliError(error: unknown, json: boolean): void {
ok: false,
error: {
code: error instanceof RuntimeClientError ? error.code : 'runtime_error',
message: formatCliError(error)
message: error instanceof Error ? error.message : String(error),
data: localCliErrorData(error, context)
},
_meta: {
runtimeId: null
@@ -98,10 +121,28 @@ export function reportCliError(error: unknown, json: boolean): void {
console.log(JSON.stringify(response, null, 2))
}
} else {
console.error(formatCliError(error))
console.error(formatCliError(error, context))
}
}
function formatMessageWithNextSteps(message: string, nextSteps: readonly string[]): string {
if (nextSteps.length === 0) {
return message
}
return `${message}\n${nextSteps.map((step) => `Next step: ${step}`).join('\n')}`
}
function localCliErrorData(error: unknown, context: CliErrorContext): unknown {
if (
error instanceof RuntimeClientError &&
error.code === 'invalid_argument' &&
context.commandPath?.[0] === 'computer'
) {
return computerUseErrorRecoveryData('invalid_argument')
}
return undefined
}
export function formatCliStatus(status: CliStatusResult): string {
return [
`appRunning: ${status.app.running}`,
@@ -116,672 +157,3 @@ export function formatCliStatus(status: CliStatusResult): string {
export function formatStatus(status: CliStatusResult): string {
return formatCliStatus(status)
}
export function formatMemorySnapshot(snapshot: MemorySnapshot): string {
const topWorktrees = [...snapshot.worktrees].sort((a, b) => b.memory - a.memory).slice(0, 10)
const lines = [
`collectedAt: ${new Date(snapshot.collectedAt).toISOString()}`,
`totalMemory: ${formatByteCount(snapshot.totalMemory)}`,
`totalCpu: ${formatCpu(snapshot.totalCpu)}`,
[
`hostUsed: ${formatByteCount(snapshot.host.usedMemory)}`,
`/ ${formatByteCount(snapshot.host.totalMemory)}`,
`(${snapshot.host.memoryUsagePercent.toFixed(1)}%)`
].join(' '),
[
`app: ${formatByteCount(snapshot.app.memory)}`,
`(main ${formatByteCount(snapshot.app.main.memory)},`,
`renderer ${formatByteCount(snapshot.app.renderer.memory)},`,
`other ${formatByteCount(snapshot.app.other.memory)})`
].join(' '),
`worktrees: ${snapshot.worktrees.length}`
]
if (topWorktrees.length === 0) {
lines.push('topWorktrees: none')
return lines.join('\n')
}
lines.push('', 'Top worktrees:')
for (const worktree of topWorktrees) {
lines.push(formatWorktreeMemoryLine(worktree))
}
if (snapshot.worktrees.length > topWorktrees.length) {
lines.push(`... ${snapshot.worktrees.length - topWorktrees.length} more worktrees`)
}
return lines.join('\n')
}
function formatWorktreeMemoryLine(worktree: WorktreeMemory): string {
return [
`- ${worktree.worktreeName}`,
`${formatByteCount(worktree.memory)}`,
`${formatCpu(worktree.cpu)}`,
`${worktree.sessions.length} session${worktree.sessions.length === 1 ? '' : 's'}`
].join(' ')
}
function formatCpu(cpu: number): string {
return `${cpu.toFixed(1)}%`
}
function formatByteCount(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) {
return '0 B'
}
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let value = bytes
let unitIndex = 0
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024
unitIndex += 1
}
const formatted = value >= 10 || unitIndex === 0 ? value.toFixed(0) : value.toFixed(1)
return `${formatted} ${units[unitIndex]}`
}
export function formatEnvironmentList(result: {
environments: PublicKnownRuntimeEnvironment[]
}): string {
if (result.environments.length === 0) {
return 'No saved environments.'
}
return result.environments
.map(
(environment) =>
`${environment.id} ${environment.name} ${environment.endpoints[0]?.endpoint ?? 'no-endpoint'}`
)
.join('\n')
}
export function formatEnvironment(environment: PublicKnownRuntimeEnvironment): string {
return [
`id: ${environment.id}`,
`name: ${environment.name}`,
`runtimeId: ${environment.runtimeId ?? 'unknown'}`,
`lastUsedAt: ${environment.lastUsedAt ?? 'never'}`,
`preferredEndpointId: ${environment.preferredEndpointId}`,
...environment.endpoints.map(
(endpoint) => `endpoint: ${endpoint.id} ${endpoint.kind} ${endpoint.endpoint}`
)
].join('\n')
}
export function formatTerminalList(result: RuntimeTerminalListResult): string {
if (result.terminals.length === 0) {
return 'No live terminals.'
}
const body = result.terminals
.map(
(terminal) =>
`${terminal.handle} ${terminal.title ?? '(untitled)'} ${terminal.connected ? 'connected' : 'disconnected'} ${terminal.worktreePath}\n${terminal.preview ? `preview: ${terminal.preview}` : 'preview: <empty>'}`
)
.join('\n\n')
return result.truncated
? `${body}\n\ntruncated: showing ${result.terminals.length} of ${result.totalCount}`
: body
}
export function formatTerminalShow(result: { terminal: RuntimeTerminalShow }): string {
const terminal = result.terminal
return [
`handle: ${terminal.handle}`,
`title: ${terminal.title ?? '(untitled)'}`,
`worktree: ${terminal.worktreePath}`,
`branch: ${terminal.branch}`,
`leaf: ${terminal.leafId}`,
`ptyId: ${terminal.ptyId ?? 'none'}`,
`connected: ${terminal.connected}`,
`writable: ${terminal.writable}`,
`preview: ${terminal.preview || '<empty>'}`
].join('\n')
}
export function formatTerminalRead(result: { terminal: RuntimeTerminalRead }): string {
const terminal = result.terminal
const oldestCursor =
typeof terminal.oldestCursor === 'string' ? [`oldest cursor: ${terminal.oldestCursor}`] : []
const latestCursor =
typeof terminal.latestCursor === 'string' ? [`latest cursor: ${terminal.latestCursor}`] : []
const limitedWarning = formatTerminalReadLimitedWarning(terminal)
const header = [
`handle: ${terminal.handle}`,
`status: ${terminal.status}`,
...(terminal.nextCursor !== null ? [`cursor: ${terminal.nextCursor}`] : []),
...oldestCursor,
...latestCursor,
...(terminal.truncated ? ['warning: older output is no longer retained'] : []),
...(limitedWarning ? [limitedWarning] : [])
]
return [...header, '', ...terminal.tail].join('\n')
}
function formatTerminalReadLimitedWarning(terminal: RuntimeTerminalRead): string | null {
if (!terminal.limited) {
return null
}
if (
typeof terminal.nextCursor === 'string' &&
typeof terminal.latestCursor === 'string' &&
terminal.nextCursor !== terminal.latestCursor
) {
return `warning: output limited; continue with --cursor ${terminal.nextCursor}`
}
if (
typeof terminal.oldestCursor === 'string' &&
typeof terminal.latestCursor === 'string' &&
terminal.oldestCursor !== terminal.latestCursor
) {
// A tail preview's next cursor is already latest, so oldestCursor is the retained history entry point.
return `warning: output limited; page retained output with --cursor ${terminal.oldestCursor} --limit <count>`
}
return 'warning: output limited'
}
export function formatTerminalSend(result: { send: RuntimeTerminalSend }): string {
return `Sent ${result.send.bytesWritten} bytes to ${result.send.handle}.`
}
export function formatTerminalRename(result: { rename: RuntimeTerminalRename }): string {
return result.rename.title
? `Renamed terminal ${result.rename.handle} to "${result.rename.title}".`
: `Cleared title for terminal ${result.rename.handle}.`
}
export function formatTerminalCreate(result: { terminal: RuntimeTerminalCreate }): string {
const titleNote = result.terminal.title ? ` (title: "${result.terminal.title}")` : ''
const surfaceNote = result.terminal.surface ? ` [${result.terminal.surface}]` : ''
return `Created terminal ${result.terminal.handle}${titleNote}${surfaceNote}`
}
export function formatTerminalSplit(result: { split: RuntimeTerminalSplit }): string {
return `Split pane ${result.split.handle} in tab ${result.split.tabId}`
}
export function formatTerminalFocus(result: { focus: RuntimeTerminalFocus }): string {
return `Focused terminal ${result.focus.handle} (tab ${result.focus.tabId}).`
}
export function formatTerminalClose(result: { close: RuntimeTerminalClose }): string {
const ptyNote = result.close.ptyKilled ? ' PTY killed.' : ''
return `Closed terminal ${result.close.handle}.${ptyNote}`
}
export function formatTerminalWait(result: { wait: RuntimeTerminalWait }): string {
const lines = [
`handle: ${result.wait.handle}`,
`condition: ${result.wait.condition}`,
`satisfied: ${result.wait.satisfied}`,
`status: ${result.wait.status}`,
`exitCode: ${result.wait.exitCode ?? 'null'}`
]
if (result.wait.blockedReason) {
lines.push(`blockedReason: ${result.wait.blockedReason}`)
}
return lines.join('\n')
}
export function formatWorktreePs(result: RuntimeWorktreePsResult): string {
if (result.worktrees.length === 0) {
return 'No worktrees found.'
}
const body = result.worktrees
.map(
(worktree) =>
`${worktree.repo} ${worktree.branch} live:${worktree.liveTerminalCount} pty:${worktree.hasAttachedPty ? 'yes' : 'no'} unread:${worktree.unread ? 'yes' : 'no'}\n${worktree.path}${worktree.preview ? `\npreview: ${worktree.preview}` : ''}`
)
.join('\n\n')
return result.truncated
? `${body}\n\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: body
}
export function formatRepoList(result: RuntimeRepoList): string {
if (result.repos.length === 0) {
return 'No repos found.'
}
return result.repos.map((repo) => `${repo.id} ${repo.displayName} ${repo.path}`).join('\n')
}
export function formatRepoShow(result: { repo: Record<string, unknown> }): string {
return Object.entries(result.repo)
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
}
export function formatRepoRefs(result: RuntimeRepoSearchRefs): string {
if (result.refs.length === 0) {
return 'No refs found.'
}
return result.truncated ? `${result.refs.join('\n')}\n\ntruncated: yes` : result.refs.join('\n')
}
export function formatWorktreeList(result: RuntimeWorktreeListResult): string {
if (result.worktrees.length === 0) {
return 'No worktrees found.'
}
const body = result.worktrees
.map((worktree) => {
const childCount = worktree.childWorktreeIds?.length ?? 0
return `${String(worktree.id)} ${String(worktree.branch)} ${String(worktree.path)}\ndisplayName: ${String(worktree.displayName ?? '')}\nparentWorktreeId: ${String(worktree.parentWorktreeId ?? 'null')}\nchildWorktreeIds: ${childCount > 0 ? worktree.childWorktreeIds.join(',') : '[]'}\nlinkedIssue: ${String(worktree.linkedIssue ?? 'null')}\ncomment: ${String(worktree.comment ?? '')}`
})
.join('\n\n')
return result.truncated
? `${body}\n\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: body
}
export function formatWorktreeShow(result: { worktree: RuntimeWorktreeRecord }): string {
const worktree = result.worktree
return Object.entries(worktree)
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
}
export function formatAutomationList(result: { automations: Automation[] }): string {
if (result.automations.length === 0) {
return 'No automations found.'
}
return result.automations
.map((automation) => {
const status = automation.enabled ? 'enabled' : 'disabled'
return `${automation.id} ${automation.name} ${automation.agentId} ${status}\n${formatAutomationSchedule(automation.rrule)} next: ${new Date(automation.nextRunAt).toISOString()}`
})
.join('\n\n')
}
export function formatAutomationShow(result: { automation: Automation }): string {
const automation = result.automation
return [
`id: ${automation.id}`,
`name: ${automation.name}`,
`provider: ${automation.agentId}`,
`enabled: ${automation.enabled}`,
`schedule: ${formatAutomationSchedule(automation.rrule)}`,
`rrule: ${automation.rrule}`,
`precheck: ${
automation.precheck
? `${automation.precheck.command} (timeout ${formatAutomationPrecheckTimeout(
automation.precheck.timeoutSeconds
)})`
: 'none'
}`,
`nextRunAt: ${new Date(automation.nextRunAt).toISOString()}`,
`projectId: ${automation.projectId}`,
`workspaceMode: ${automation.workspaceMode}`,
`workspaceId: ${automation.workspaceId ?? 'null'}`,
`baseBranch: ${automation.baseBranch ?? 'null'}`,
`reuseSession: ${automation.reuseSession}`,
`target: ${automation.executionTargetType}:${automation.executionTargetId}`,
`prompt: ${automation.prompt}`
].join('\n')
}
export function formatAutomationRemoved(result: { removed: boolean; id: string }): string {
return result.removed
? `Removed automation ${result.id}.`
: `Automation ${result.id} not removed.`
}
export function formatAutomationRun(result: { run: AutomationRun }): string {
return [
`id: ${result.run.id}`,
`automationId: ${result.run.automationId}`,
`title: ${result.run.title}`,
`status: ${result.run.status}`,
`trigger: ${result.run.trigger}`,
`scheduledFor: ${new Date(result.run.scheduledFor).toISOString()}`,
`workspaceId: ${result.run.workspaceId ?? 'null'}`,
`precheck: ${formatAutomationRunPrecheck(result.run)}`,
`error: ${result.run.error ?? 'null'}`
].join('\n')
}
function formatAutomationRunPrecheck(run: AutomationRun): string {
const result = run.precheckResult
if (!result) {
return 'none'
}
const outcome = result.timedOut
? 'timed out'
: result.error
? 'error'
: `exit ${result.exitCode ?? 'unknown'}`
const output = result.stderr.trim() || result.stdout.trim()
return output ? `${outcome}; ${output}` : outcome
}
export function formatAutomationRuns(result: { runs: AutomationRun[] }): string {
if (result.runs.length === 0) {
return 'No automation runs found.'
}
return result.runs
.map(
(run) =>
`${run.id} ${run.automationId} ${run.status} ${run.trigger} ${new Date(run.scheduledFor).toISOString()}\n${run.title}${run.precheckResult ? `\nprecheck: ${formatAutomationRunPrecheck(run)}` : ''}${run.error ? `\nerror: ${run.error}` : ''}`
)
.join('\n\n')
}
export function formatSnapshot(result: BrowserSnapshotResult): string {
const header = `page: ${result.browserPageId}\n${result.title} — ${result.url}\n`
return header + result.snapshot
}
export function formatScreenshot(result: BrowserScreenshotResult): string {
return `Screenshot captured (${result.format}, ${Math.round(result.data.length * 0.75)} bytes)`
}
export function formatTabList(result: BrowserTabListResult): string {
return formatTabListWithProfiles(result, false)
}
export function formatTabListWithProfiles(
result: BrowserTabListResult,
showProfile: boolean
): string {
if (result.tabs.length === 0) {
return 'No browser tabs open.'
}
return result.tabs
.map((t) => {
const marker = t.active ? '* ' : ' '
const profile = showProfile ? ` [${t.profileLabel ?? t.profileId ?? 'Unknown'}]` : ''
return `${marker}[${t.index}] ${t.browserPageId} ${t.title} — ${t.url}${profile}`
})
.join('\n')
}
export function formatBrowserProfileList(result: BrowserProfileListResult): string {
if (result.profiles.length === 0) {
return 'No browser profiles found.'
}
return result.profiles
.map((profile) => {
const marker = profile.scope === 'default' ? '* ' : ' '
const source = profile.source?.browserFamily ?? 'none'
return `${marker}${profile.id} ${profile.label} ${profile.scope} source:${source}`
})
.join('\n')
}
export function formatTabShow(result: BrowserTabShowResult | BrowserTabCurrentResult): string {
const tab = result.tab
return [
`page: ${tab.browserPageId}`,
`title: ${tab.title}`,
`url: ${tab.url}`,
`active: ${tab.active}`,
`worktree: ${tab.worktreeId ?? 'unknown'}`,
`profile: ${tab.profileLabel ?? tab.profileId ?? 'unknown'}`
].join('\n')
}
export function formatTabProfileShow(result: BrowserTabProfileShowResult): string {
return [
`page: ${result.browserPageId}`,
`worktree: ${result.worktreeId ?? 'unknown'}`,
`profileId: ${result.profileId ?? 'default'}`,
`profile: ${result.profileLabel ?? result.profileId ?? 'default'}`
].join('\n')
}
export function formatTabProfileClone(result: BrowserTabProfileCloneResult): string {
return `Cloned ${result.sourceBrowserPageId} to ${result.browserPageId} (${result.profileLabel ?? result.profileId ?? 'default'})`
}
export function formatGetAppState(result: ComputerSnapshotResult): string {
const app = result.snapshot.app
const bundle = app.bundleId ? `, ${app.bundleId}` : ''
const focused =
result.snapshot.focusedElementId === null ? 'none' : `#${result.snapshot.focusedElementId}`
const windowId =
result.snapshot.window.id === null || result.snapshot.window.id === undefined
? ''
: ` id:${result.snapshot.window.id}`
const origin =
result.snapshot.window.x === null ||
result.snapshot.window.x === undefined ||
result.snapshot.window.y === null ||
result.snapshot.window.y === undefined
? ''
: ` @ ${result.snapshot.window.x},${result.snapshot.window.y}`
const truncation = result.snapshot.truncation?.truncated
? ` Truncated: yes (max nodes ${result.snapshot.truncation.maxNodes ?? 'unknown'}, max depth ${result.snapshot.truncation.maxDepth ?? 'unknown'})`
: ' Truncated: no'
return [
`${app.name} (pid ${app.pid}${bundle})`,
` Window:${windowId} "${result.snapshot.window.title}" (${result.snapshot.window.width}x${result.snapshot.window.height}${origin})`,
` Elements: ${result.snapshot.elementCount} Focused: ${focused} Coordinates: ${result.snapshot.coordinateSpace}`,
truncation,
` ${formatComputerScreenshotStatus(result)}`,
'',
result.snapshot.treeText
].join('\n')
}
function prepareCliJsonResult<TResult>(
response: RuntimeRpcSuccess<TResult>
): RuntimeRpcSuccess<TResult> {
const record = response as RuntimeRpcSuccess<TResult> & {
result?: { screenshot?: { data?: unknown; format?: unknown; path?: unknown } | null }
}
const screenshot = record.result?.screenshot
if (!screenshot || typeof screenshot.data !== 'string' || screenshot.data.length === 0) {
return response
}
const extension = screenshot.format === 'png' ? 'png' : 'img'
const outputDir = computerScreenshotTempDir()
cleanupComputerScreenshots(outputDir)
const outputPath = join(outputDir, `${safeCliFileStem(response.id)}-screenshot.${extension}`)
writeFileSync(outputPath, Buffer.from(screenshot.data, 'base64'), { mode: 0o600 })
const expiresAt = new Date(Date.now() + COMPUTER_SCREENSHOT_TTL_MS).toISOString()
return {
...response,
result: {
...record.result,
screenshot: {
...screenshot,
data: undefined,
path: outputPath,
dataOmitted: true,
expiresAt
}
}
} as RuntimeRpcSuccess<TResult>
}
const COMPUTER_SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000
const COMPUTER_SCREENSHOT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000
const COMPUTER_SCREENSHOT_CLEANUP_MARKER = '.last-cleanup'
function computerScreenshotTempDir(): string {
const outputDir =
process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR || join(tmpdir(), 'orca-computer-use')
mkdirSync(outputDir, { recursive: true, mode: 0o700 })
const stat = lstatSync(outputDir)
if (!stat.isDirectory() || stat.isSymbolicLink()) {
throw new Error(`Unsafe computer screenshot temp path: ${outputDir}`)
}
if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
throw new Error(`Computer screenshot temp path is not owned by the current user: ${outputDir}`)
}
chmodSync(outputDir, 0o700)
return outputDir
}
function cleanupComputerScreenshots(outputDir: string): void {
const now = Date.now()
const markerPath = join(outputDir, COMPUTER_SCREENSHOT_CLEANUP_MARKER)
try {
// Why: agents can call computer-use CLI commands in loops; a marker keeps
// temp cleanup from becoming a synchronous directory scan per screenshot.
if (statSync(markerPath).mtimeMs > now - COMPUTER_SCREENSHOT_CLEANUP_INTERVAL_MS) {
return
}
} catch {
// Missing or unreadable marker means this process should attempt cleanup.
}
const cutoff = now - COMPUTER_SCREENSHOT_TTL_MS
for (const entry of readdirSync(outputDir)) {
if (!entry.endsWith('-screenshot.png') && !entry.endsWith('-screenshot.img')) {
continue
}
const path = join(outputDir, entry)
try {
if (statSync(path).mtimeMs < cutoff) {
rmSync(path, { force: true })
}
} catch {
// Best-effort cleanup only; formatting should not fail because a temp file raced.
}
}
try {
writeFileSync(markerPath, `${now}\n`, { mode: 0o600 })
} catch {
// Best-effort marker only; stale cleanup state should not hide a screenshot.
}
}
function safeCliFileStem(value: string): string {
return value.replaceAll(/[^a-zA-Z0-9._-]/g, '_')
}
export function formatListApps(result: ComputerListAppsResult): string {
if (result.apps.length === 0) {
return 'No apps found.'
}
return result.apps
.map((app) => {
const bundle = app.bundleId ? ` ${app.bundleId}` : ''
return `${app.name} pid:${app.pid}${bundle}`
})
.join('\n')
}
export function formatListWindows(result: ComputerListWindowsResult): string {
if (result.windows.length === 0) {
return `No windows found for ${result.app.name}.`
}
return result.windows
.map((window) => {
const id = window.id === null || window.id === undefined ? 'none' : String(window.id)
const origin =
window.x === null || window.x === undefined || window.y === null || window.y === undefined
? ''
: ` @ ${window.x},${window.y}`
const screen =
window.screenIndex === null || window.screenIndex === undefined
? ''
: ` screen:${window.screenIndex}`
const state = [
window.isMinimized ? 'minimized' : null,
window.isOffscreen ? 'offscreen' : null
].filter(Boolean)
const stateText = state.length > 0 ? ` ${state.join(',')}` : ''
return `[${window.index}] id:${id} "${window.title}" (${window.width}x${window.height}${origin})${screen}${stateText}`
})
.join('\n')
}
export type ComputerActionFollowUpTarget = {
session?: string
worktree?: string
windowId?: number
windowIndex?: number
restoreWindow?: boolean
}
export function formatComputerAction(
verb: string,
result: ComputerActionResult,
target: ComputerActionFollowUpTarget = {}
): string {
const path = result.action?.path ? ` via ${result.action.path}` : ''
const verification = formatActionVerification(result.action?.verification)
const followUpCommand = formatComputerFollowUpCommand(result, target)
return `${formatActionVerb(verb)} completed${path}${verification}; ${result.snapshot.elementCount} elements in current window. Use \`${followUpCommand}\` to inspect.`
}
function formatComputerFollowUpCommand(
result: ComputerActionResult,
target: ComputerActionFollowUpTarget
): string {
const args = [
'orca',
'computer',
'get-app-state',
'--app',
shellQuote(result.snapshot.app.bundleId ?? result.snapshot.app.name)
]
if (target.session) {
args.push('--session', shellQuote(target.session))
} else if (target.worktree) {
args.push('--worktree', shellQuote(target.worktree))
}
if (target.windowId !== undefined) {
args.push('--window-id', String(target.windowId))
} else if (target.windowIndex !== undefined) {
args.push('--window-index', String(target.windowIndex))
} else {
const windowId = result.action?.targetWindowId ?? result.snapshot.window.id
if (windowId !== null && windowId !== undefined) {
args.push('--window-id', String(windowId))
}
}
if (target.restoreWindow) {
args.push('--restore-window')
}
return args.join(' ')
}
function formatActionVerification(verification: ComputerActionVerification | undefined): string {
if (!verification) {
return ''
}
if (verification.state === 'verified') {
return `, verified ${verification.property}`
}
return `, unverified (${verification.reason.replaceAll('_', ' ')})`
}
function formatComputerScreenshotStatus(result: ComputerSnapshotResult): string {
if (result.screenshotStatus.state === 'captured' && result.screenshot) {
const bytes = result.screenshot.data
? `${Math.round(result.screenshot.data.length * 0.75)} bytes`
: `saved to ${result.screenshot.path ?? 'temporary file'}`
const engine = result.screenshotStatus.metadata?.engine
const detail = engine
? `${result.screenshot.format}, ${bytes}, ${engine}`
: `${result.screenshot.format}, ${bytes}`
return `Screenshot captured (${detail})`
}
if (result.screenshotStatus.state === 'skipped') {
return 'Screenshot skipped (--no-screenshot)'
}
if (result.screenshotStatus.state === 'failed') {
return `Screenshot failed (${result.screenshotStatus.code}): ${result.screenshotStatus.message}`
}
return 'Screenshot was not captured'
}
function shellQuote(value: string): string {
if (/^[a-zA-Z0-9._:/@-]+$/.test(value)) {
return value
}
return `'${value.replaceAll("'", "'\\''")}'`
}
function formatActionVerb(verb: string): string {
return verb
.split('-')
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ')
}
@@ -0,0 +1,105 @@
import { RuntimeClientError } from '../runtime-client'
export function validateExclusiveWindowTarget(
windowId: number | undefined,
windowIndex: number | undefined
): void {
if (windowId !== undefined && windowIndex !== undefined) {
throw new RuntimeClientError(
'invalid_argument',
'Window targeting accepts either --window-id or --window-index, not both'
)
}
}
export function validateElementOrCoordinates(
actionName: 'Click' | 'Scroll',
elementIndex: number | undefined,
x: number | undefined,
y: number | undefined
): void {
const hasElement = elementIndex !== undefined
const hasX = x !== undefined
const hasY = y !== undefined
if (!hasElement && !(hasX && hasY)) {
throw new RuntimeClientError(
'invalid_argument',
`${actionName} requires --element-index or both --x and --y`
)
}
if (hasX !== hasY) {
throw new RuntimeClientError(
'invalid_argument',
`${actionName} coordinates require both --x and --y`
)
}
if (hasElement && (hasX || hasY)) {
throw new RuntimeClientError(
'invalid_argument',
`${actionName} accepts either --element-index or coordinate flags, not both`
)
}
}
export function validateDragTarget(value: {
fromElementIndex?: number
toElementIndex?: number
fromX?: number
fromY?: number
toX?: number
toY?: number
}): void {
const hasElementPair = value.fromElementIndex !== undefined && value.toElementIndex !== undefined
const hasPartialElementPair =
value.fromElementIndex !== undefined || value.toElementIndex !== undefined
const coordinates = [value.fromX, value.fromY, value.toX, value.toY]
const hasCoordinatePair = coordinates.every((coordinate) => coordinate !== undefined)
const hasPartialCoordinatePair = coordinates.some((coordinate) => coordinate !== undefined)
if (hasElementPair && hasCoordinatePair) {
throw new RuntimeClientError(
'invalid_argument',
'Drag accepts either element indexes or coordinate flags, not both'
)
}
if (hasPartialElementPair && !hasElementPair) {
throw new RuntimeClientError(
'invalid_argument',
'Drag element targeting requires both --from-element-index and --to-element-index'
)
}
if (hasPartialCoordinatePair && !hasCoordinatePair) {
throw new RuntimeClientError(
'invalid_argument',
'Drag coordinates require --from-x, --from-y, --to-x, and --to-y'
)
}
if (!hasElementPair && !hasCoordinatePair) {
throw new RuntimeClientError(
'invalid_argument',
'Drag requires --from-element-index and --to-element-index, or all coordinate flags'
)
}
}
export function validateMouseButton(mouseButton: string | undefined): void {
if (
mouseButton !== undefined &&
mouseButton !== 'left' &&
mouseButton !== 'right' &&
mouseButton !== 'middle'
) {
throw new RuntimeClientError(
'invalid_argument',
'Unsupported --mouse-button; expected left, right, or middle'
)
}
}
export function validateScrollDirection(direction: string): void {
if (direction !== 'up' && direction !== 'down' && direction !== 'left' && direction !== 'right') {
throw new RuntimeClientError(
'invalid_argument',
'Unsupported --direction; expected up, down, left, or right'
)
}
}
+222
View File
@@ -0,0 +1,222 @@
import {
computerUseHotkeyValidationMessage,
computerUsePressKeyValidationMessage
} from '../../shared/computer-use-key-spec'
import {
getOptionalNonNegativeIntegerFlag,
getOptionalNumberFlag,
getOptionalPositiveIntegerFlag,
getOptionalStringFlag,
getRequiredStringFlag,
getRequiredStringFlagAllowingEmpty
} from '../flags'
import { RuntimeClientError } from '../runtime-client'
import {
validateDragTarget,
validateElementOrCoordinates,
validateExclusiveWindowTarget,
validateMouseButton,
validateScrollDirection
} from './computer-action-flag-validation'
export function getComputerWindowTargetFlags(flags: Map<string, string | boolean>): {
windowId?: number
windowIndex?: number
} {
const windowId = getOptionalNonNegativeIntegerFlag(flags, 'window-id')
const windowIndex = getOptionalNonNegativeIntegerFlag(flags, 'window-index')
validateExclusiveWindowTarget(windowId, windowIndex)
return {
...(windowId !== undefined ? { windowId } : {}),
...(windowIndex !== undefined ? { windowIndex } : {})
}
}
export function getComputerObserveFlags(flags: Map<string, string | boolean>): {
noScreenshot?: boolean
restoreWindow?: boolean
windowId?: number
windowIndex?: number
} {
return {
noScreenshot: flags.has('no-screenshot') ? true : undefined,
...(flags.has('restore-window') ? { restoreWindow: true } : {}),
...getComputerWindowTargetFlags(flags)
}
}
export function getComputerActionObserveFlags(flags: Map<string, string | boolean>): {
noScreenshot?: boolean
restoreWindow?: boolean
windowId?: number
windowIndex?: number
} {
return getComputerObserveFlags(flags)
}
export function getComputerClickActionFlags(flags: Map<string, string | boolean>): {
elementIndex?: number
x?: number
y?: number
clickCount?: number
mouseButton?: string
} {
const result = {
elementIndex: getOptionalNonNegativeIntegerFlag(flags, 'element-index'),
x: getOptionalNumberFlag(flags, 'x'),
y: getOptionalNumberFlag(flags, 'y'),
clickCount: getOptionalPositiveIntegerFlag(flags, 'click-count'),
mouseButton: getOptionalStringFlag(flags, 'mouse-button')
}
validateElementOrCoordinates('Click', result.elementIndex, result.x, result.y)
validateMouseButton(result.mouseButton)
return result
}
export function getComputerSecondaryActionFlags(flags: Map<string, string | boolean>): {
elementIndex: number
action: string
} {
return {
elementIndex: getRequiredNonNegativeIntegerFlag(flags, 'element-index'),
action: getRequiredStringFlag(flags, 'action')
}
}
export function getComputerScrollActionFlags(flags: Map<string, string | boolean>): {
elementIndex?: number
x?: number
y?: number
direction: string
pages?: number
} {
const result = {
elementIndex: getOptionalNonNegativeIntegerFlag(flags, 'element-index'),
x: getOptionalNumberFlag(flags, 'x'),
y: getOptionalNumberFlag(flags, 'y'),
direction: getRequiredStringFlag(flags, 'direction'),
pages: getOptionalPositiveNumberFlag(flags, 'pages')
}
validateElementOrCoordinates('Scroll', result.elementIndex, result.x, result.y)
validateScrollDirection(result.direction)
return result
}
export function getComputerDragActionFlags(flags: Map<string, string | boolean>): {
fromElementIndex?: number
toElementIndex?: number
fromX?: number
fromY?: number
toX?: number
toY?: number
} {
const result = {
fromElementIndex: getOptionalNonNegativeIntegerFlag(flags, 'from-element-index'),
toElementIndex: getOptionalNonNegativeIntegerFlag(flags, 'to-element-index'),
fromX: getOptionalNumberFlag(flags, 'from-x'),
fromY: getOptionalNumberFlag(flags, 'from-y'),
toX: getOptionalNumberFlag(flags, 'to-x'),
toY: getOptionalNumberFlag(flags, 'to-y')
}
validateDragTarget(result)
return result
}
export async function getComputerTextActionFlags(flags: Map<string, string | boolean>): Promise<{
text: string
}> {
return { text: await getTextPayload(flags, 'text') }
}
export function getComputerKeyActionFlags(flags: Map<string, string | boolean>): {
key: string
} {
const key = getRequiredStringFlag(flags, 'key')
const message = computerUsePressKeyValidationMessage(key)
if (message) {
throw new RuntimeClientError('invalid_argument', message)
}
return { key }
}
export function getComputerHotkeyActionFlags(flags: Map<string, string | boolean>): {
key: string
} {
const key = getRequiredStringFlag(flags, 'key')
const message = computerUseHotkeyValidationMessage(key)
if (message) {
throw new RuntimeClientError('invalid_argument', message)
}
return { key }
}
export async function getComputerSetValueActionFlags(
flags: Map<string, string | boolean>
): Promise<{
elementIndex: number
value: string
}> {
return {
elementIndex: getRequiredNonNegativeIntegerFlag(flags, 'element-index'),
value: await getTextPayload(flags, 'value')
}
}
async function getTextPayload(
flags: Map<string, string | boolean>,
name: 'text' | 'value'
): Promise<string> {
const stdinFlag = `${name}-stdin`
if (flags.has(stdinFlag)) {
if (flags.has(name)) {
throw new RuntimeClientError(
'invalid_argument',
`Use either --${name} or --${stdinFlag}, not both`
)
}
const payload = await readStdin()
if (name === 'text' && payload.length === 0) {
throw new RuntimeClientError('invalid_argument', 'Missing text from stdin')
}
return payload
}
return name === 'value'
? getRequiredStringFlagAllowingEmpty(flags, name)
: getRequiredStringFlag(flags, name)
}
async function readStdin(): Promise<string> {
if (process.stdin.isTTY) {
throw new RuntimeClientError('invalid_argument', 'stdin payload requested but stdin is a TTY')
}
const chunks: Buffer[] = []
for await (const chunk of process.stdin) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
}
return Buffer.concat(chunks).toString('utf8')
}
function getOptionalPositiveNumberFlag(
flags: Map<string, string | boolean>,
name: string
): number | undefined {
const value = getOptionalNumberFlag(flags, name)
if (value === undefined) {
return undefined
}
if (value <= 0) {
throw new RuntimeClientError('invalid_argument', `Invalid positive number for --${name}`)
}
return value
}
function getRequiredNonNegativeIntegerFlag(
flags: Map<string, string | boolean>,
name: string
): number {
const value = getOptionalNonNegativeIntegerFlag(flags, name)
if (value === undefined) {
throw new RuntimeClientError('invalid_argument', `Missing required --${name}`)
}
return value
}
@@ -0,0 +1,247 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime-client', () => {
class RuntimeClient {
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
}
class RuntimeClientError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
class RuntimeRpcFailureError extends RuntimeClientError {
readonly response: unknown
constructor(response: unknown) {
super('runtime_error', 'runtime_error')
this.response = response
}
}
return {
RuntimeClient,
RuntimeClientError,
RuntimeRpcFailureError
}
})
import { main } from '../index'
import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from '../test-fixtures'
describe('orca computer action CLI routing', () => {
beforeEach(() => {
vi.restoreAllMocks()
callMock.mockReset()
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
process.exitCode = undefined
})
it('does not resolve worktree when --session is explicit', async () => {
queueFixtures(callMock, okFixture('req_click', sampleSnapshot()))
await main(
[
'computer',
'click',
'--session',
'manual',
'--app',
'Finder',
'--element-index',
'3',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledTimes(1)
expect(callMock).toHaveBeenCalledWith('computer.click', {
session: 'manual',
app: 'Finder',
elementIndex: 3,
x: undefined,
y: undefined,
clickCount: undefined,
mouseButton: undefined,
noScreenshot: undefined
})
})
it('prints session and window context in action follow-up commands', async () => {
queueFixtures(callMock, okFixture('req_click', sampleSnapshot()))
await main(
[
'computer',
'click',
'--session',
'manual',
'--app',
'Finder',
'--element-index',
'3',
'--window-index',
'1',
'--restore-window'
],
'/tmp/repo/src'
)
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).toContain(
'Use `orca computer get-app-state --app com.apple.finder --session manual --window-index 1 --restore-window`'
)
})
it('maps action command flags to RPC payloads', async () => {
queueFixtures(
callMock,
worktreeListFixture([buildWorktree('/tmp/repo', 'feature')]),
okFixture('req_drag', sampleSnapshot())
)
await main(
[
'computer',
'drag',
'--app',
'Finder',
'--from-x',
'1',
'--from-y',
'2',
'--to-x',
'3',
'--to-y',
'4',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenNthCalledWith(2, 'computer.drag', {
app: 'Finder',
worktree: 'id:repo::/tmp/repo',
fromElementIndex: undefined,
toElementIndex: undefined,
fromX: 1,
fromY: 2,
toX: 3,
toY: 4,
noScreenshot: undefined
})
})
it('maps coordinate scroll flags to RPC payloads', async () => {
queueFixtures(callMock, okFixture('req_scroll', sampleSnapshot()))
await main(
[
'computer',
'scroll',
'--session',
'manual',
'--app',
'Finder',
'--x',
'10',
'--y',
'20',
'--direction',
'down',
'--pages',
'0.5',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.scroll', {
session: 'manual',
app: 'Finder',
elementIndex: undefined,
x: 10,
y: 20,
direction: 'down',
pages: 0.5,
noScreenshot: undefined
})
})
it('maps hotkey and paste-text command flags to RPC payloads', async () => {
queueFixtures(callMock, okFixture('req_hotkey', sampleSnapshot()))
await main(
[
'computer',
'hotkey',
'--session',
'manual',
'--app',
'Finder',
'--key',
'CmdOrCtrl+L',
'--no-screenshot',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.hotkey', {
session: 'manual',
app: 'Finder',
key: 'CmdOrCtrl+L',
noScreenshot: true
})
callMock.mockReset()
vi.mocked(console.log).mockClear()
queueFixtures(callMock, okFixture('req_paste', sampleSnapshot()))
await main(
[
'computer',
'paste-text',
'--session',
'manual',
'--app',
'Finder',
'--text',
'hello world',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.pasteText', {
session: 'manual',
app: 'Finder',
text: 'hello world',
noScreenshot: undefined
})
})
})
function sampleSnapshot() {
return {
snapshot: {
id: 'snap-test',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', width: 800, height: 600 },
coordinateSpace: 'window',
truncation: { truncated: false, maxNodes: 1200, maxDepth: 64, maxDepthReached: false },
treeText: 'App=com.apple.finder (pid 100)\n0 standard window Finder',
elementCount: 1,
focusedElementId: 0
},
screenshotStatus: { state: 'captured' }
}
}
@@ -0,0 +1,444 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime-client', () => {
class RuntimeClient {
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
}
class RuntimeClientError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
class RuntimeRpcFailureError extends RuntimeClientError {
readonly response: unknown
constructor(response: unknown) {
super('runtime_error', 'runtime_error')
this.response = response
}
}
return {
RuntimeClient,
RuntimeClientError,
RuntimeRpcFailureError
}
})
import { main } from '../index'
import { okFixture, queueFixtures } from '../test-fixtures'
describe('orca computer action CLI validation', () => {
beforeEach(() => {
vi.restoreAllMocks()
callMock.mockReset()
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
process.exitCode = undefined
})
it('rejects conflicting session and worktree computer targets before resolving worktree', async () => {
await main(
[
'computer',
'get-app-state',
'--session',
'manual',
'--worktree',
'active',
'--app',
'Finder'
],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
const output = vi.mocked(console.error).mock.calls[0][0]
expect(output).toContain(
'Computer-use targeting accepts either --session or --worktree, not both'
)
expect(output).toContain('Next step: Do not retry the same command unchanged.')
expect(process.exitCode).toBe(1)
})
it('rejects actions without an app before resolving a worktree', async () => {
await main(['computer', 'click', '--element-index', '1'], '/tmp/repo/src')
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Missing required --app')
expect(process.exitCode).toBe(1)
})
it('does not mask missing app with action target errors', async () => {
await main(['computer', 'click'], '/tmp/repo/src')
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Missing required --app')
expect(process.exitCode).toBe(1)
})
it('rejects malformed hotkeys before calling the runtime', async () => {
await main(
['computer', 'hotkey', '--app', 'Finder', '--key', 'Return', '--json'],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
const output = JSON.parse(vi.mocked(console.log).mock.calls[0][0])
expect(output.error).toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Hotkey requires a modifier and one key')
})
expect(output.error.data.nextSteps).toEqual(
expect.arrayContaining([expect.stringContaining('Do not retry the same command unchanged')])
)
expect(process.exitCode).toBe(1)
})
it('rejects modifier chords on press-key before calling the runtime', async () => {
await main(
['computer', 'press-key', '--app', 'Finder', '--key', 'CmdOrCtrl+V', '--json'],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
const output = JSON.parse(vi.mocked(console.log).mock.calls[0][0])
expect(output.error).toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Press-key accepts one key only')
})
expect(output.error.data.nextSteps).toEqual(
expect.arrayContaining([expect.stringContaining('Do not retry the same command unchanged')])
)
expect(process.exitCode).toBe(1)
})
it('allows literal plus as a press-key key', async () => {
queueFixtures(
callMock,
okFixture('req_press_key', {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', id: 1, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 1,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'synthetic',
actionName: 'pressKey',
verification: { state: 'unverified', reason: 'synthetic_input' }
}
})
)
await main(
[
'computer',
'press-key',
'--session',
'manual',
'--app',
'Finder',
'--key',
'+',
'--no-screenshot'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.pressKey', {
session: 'manual',
app: 'Finder',
key: '+',
noScreenshot: true
})
expect(vi.mocked(console.error)).not.toHaveBeenCalled()
expect(process.exitCode).toBeUndefined()
})
it('rejects conflicting get-app-state window target flags before calling the runtime', async () => {
await main(
[
'computer',
'get-app-state',
'--app',
'Finder',
'--window-id',
'42',
'--window-index',
'0',
'--no-screenshot'
],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'either --window-id or --window-index'
)
expect(process.exitCode).toBe(1)
})
it('rejects invalid window ids before calling the runtime', async () => {
await main(
['computer', 'get-app-state', '--app', 'Finder', '--window-id', '1.5', '--json'],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
const output = JSON.parse(vi.mocked(console.log).mock.calls[0][0])
expect(output.error).toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Invalid non-negative integer for --window-id')
})
expect(process.exitCode).toBe(1)
})
it('rejects conflicting action window target flags before calling the runtime', async () => {
await main(
[
'computer',
'click',
'--app',
'Finder',
'--element-index',
'1',
'--window-id',
'42',
'--window-index',
'0',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
const output = JSON.parse(vi.mocked(console.log).mock.calls[0][0])
expect(output.error).toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('either --window-id or --window-index')
})
expect(process.exitCode).toBe(1)
})
it('rejects invalid action flags before resolving the runtime target', async () => {
await main(
['computer', 'click', '--app', 'Finder', '--element-index', '1', '--click-count', '0'],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Invalid positive integer for --click-count'
)
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Next step: Fix the command flags or RPC params exactly as described by the error message.'
)
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Next step: Do not retry the same command unchanged.'
)
expect(process.exitCode).toBe(1)
})
it('returns structured recovery data for local computer action flag errors in JSON mode', async () => {
await main(
[
'computer',
'click',
'--app',
'Finder',
'--element-index',
'1',
'--click-count',
'0',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
const output = JSON.parse(vi.mocked(console.log).mock.calls[0][0]) as {
error: { code: string; message: string; data?: { nextSteps?: string[] } }
}
expect(output.error.code).toBe('invalid_argument')
expect(output.error.message).toContain('Invalid positive integer for --click-count')
expect(output.error.data?.nextSteps).toEqual([
expect.stringContaining('Fix the command flags'),
expect.stringContaining('Do not retry')
])
expect(process.exitCode).toBe(1)
})
it('rejects incomplete pointer action targets before resolving the runtime target', async () => {
await main(['computer', 'click', '--app', 'Finder', '--x', '10'], '/tmp/repo/src')
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Click requires --element-index or both --x and --y'
)
expect(process.exitCode).toBe(1)
})
it('rejects unsupported action option values before resolving the runtime target', async () => {
await main(
['computer', 'click', '--app', 'Finder', '--element-index', '1', '--mouse-button', 'primary'],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Unsupported --mouse-button')
expect(process.exitCode).toBe(1)
vi.mocked(console.error).mockClear()
process.exitCode = undefined
await main(
['computer', 'scroll', '--app', 'Finder', '--element-index', '1', '--direction', 'diagonal'],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Unsupported --direction')
expect(process.exitCode).toBe(1)
})
it('rejects incomplete drag targets before resolving the runtime target', async () => {
await main(
['computer', 'drag', '--app', 'Finder', '--from-element-index', '1'],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Drag element targeting requires both --from-element-index and --to-element-index'
)
expect(process.exitCode).toBe(1)
})
it('rejects conflicting text payload flags before resolving the runtime target', async () => {
await main(
['computer', 'type-text', '--app', 'Finder', '--text', 'hello', '--text-stdin'],
'/tmp/repo/src'
)
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Use either --text or --text-stdin')
expect(process.exitCode).toBe(1)
})
it('rejects empty stdin for text actions before calling the runtime', async () => {
const stdin = mockStdin(false, [])
try {
await main(['computer', 'paste-text', '--app', 'Finder', '--text-stdin'], '/tmp/repo/src')
} finally {
stdin.restore()
}
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Missing text from stdin')
expect(process.exitCode).toBe(1)
})
it('allows empty stdin for set-value so fields can be cleared', async () => {
queueFixtures(
callMock,
okFixture('req_set_value', {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', id: 1, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 1,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'accessibility',
actionName: 'setValue',
verification: {
state: 'verified',
property: 'value',
expected: '',
actualPreview: ''
}
}
})
)
const stdin = mockStdin(false, [])
try {
await main(
[
'computer',
'set-value',
'--session',
'manual',
'--app',
'Finder',
'--element-index',
'1',
'--value-stdin',
'--no-screenshot'
],
'/tmp/repo/src'
)
} finally {
stdin.restore()
}
expect(callMock).toHaveBeenCalledWith('computer.setValue', {
session: 'manual',
app: 'Finder',
elementIndex: 1,
value: '',
noScreenshot: true
})
expect(vi.mocked(console.error)).not.toHaveBeenCalled()
expect(process.exitCode).toBeUndefined()
})
})
function mockStdin(isTTY: boolean, chunks: string[]): { restore: () => void } {
const stdin = process.stdin as typeof process.stdin & {
isTTY?: boolean
}
const previousIsTTY = stdin.isTTY
const previousAsyncIterator = stdin[Symbol.asyncIterator]
Object.defineProperty(stdin, 'isTTY', {
configurable: true,
value: isTTY
})
;(stdin as unknown as Record<symbol, unknown>)[Symbol.asyncIterator] = async function* () {
for (const chunk of chunks) {
yield Buffer.from(chunk)
}
}
return {
restore: () => {
Object.defineProperty(stdin, 'isTTY', {
configurable: true,
value: previousIsTTY
})
if (previousAsyncIterator) {
;(stdin as unknown as Record<symbol, unknown>)[Symbol.asyncIterator] = previousAsyncIterator
} else {
Reflect.deleteProperty(stdin, Symbol.asyncIterator)
}
}
}
}
@@ -0,0 +1,113 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime-client', () => {
class RuntimeClient {
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
}
class RuntimeClientError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
class RuntimeRpcFailureError extends RuntimeClientError {
readonly response: unknown
constructor(response: unknown) {
super('runtime_error', 'runtime_error')
this.response = response
}
}
return {
RuntimeClient,
RuntimeClientError,
RuntimeRpcFailureError
}
})
import { main } from '../index'
import { okFixture, queueFixtures } from '../test-fixtures'
describe('orca computer get-app-state formatting', () => {
beforeEach(() => {
vi.restoreAllMocks()
callMock.mockReset()
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
process.exitCode = undefined
})
it('formats get-app-state without printing screenshot bytes in pretty mode', async () => {
queueFixtures(callMock, okFixture('req_state', sampleSnapshot()))
await main(['computer', 'get-app-state', '--session', 'manual', '--app', 'Finder'], '/tmp/repo')
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).toContain('Finder (pid 100, com.apple.finder)')
expect(output).toContain('App=com.apple.finder')
expect(output).not.toContain('base64-data')
})
it('omits screenshot bytes from JSON output and writes a screenshot path', async () => {
queueFixtures(callMock, okFixture('req_state', sampleSnapshot()))
await main(
['computer', 'get-app-state', '--session', 'manual', '--app', 'Finder', '--json'],
'/tmp/repo'
)
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).not.toContain('base64-data')
const parsed = JSON.parse(output)
expect(parsed.result.screenshot).toMatchObject({
dataOmitted: true,
format: 'png',
expiresAt: expect.any(String)
})
expect(String(parsed.result.screenshot.path).replaceAll('\\', '/')).toContain(
'orca-computer-use/req_state-screenshot.png'
)
})
it('shows coordinate space and truncation in pretty state output', async () => {
queueFixtures(callMock, okFixture('req_state', sampleSnapshot()))
await main(['computer', 'get-app-state', '--session', 'manual', '--app', 'Finder'], '/tmp/repo')
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).toContain('Coordinates: window')
expect(output).toContain('Truncated: no')
})
})
function sampleSnapshot() {
return {
snapshot: {
id: 'snap-test',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', width: 800, height: 600 },
coordinateSpace: 'window',
truncation: { truncated: false, maxNodes: 1200, maxDepth: 64, maxDepthReached: false },
treeText: 'App=com.apple.finder (pid 100)\n0 standard window Finder',
elementCount: 1,
focusedElementId: 0
},
screenshot: {
data: 'base64-data',
format: 'png',
width: 800,
height: 600,
scale: 1
},
screenshotStatus: { state: 'captured' }
}
}
+92 -276
View File
@@ -1,4 +1,3 @@
/* eslint-disable max-lines -- Why: computer CLI coverage shares one mocked runtime setup across command contracts. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
@@ -38,11 +37,13 @@ vi.mock('../runtime-client', () => {
import { main } from '../index'
import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from '../test-fixtures'
describe('orca computer CLI handlers', () => {
describe('orca computer observation CLI handlers', () => {
beforeEach(() => {
vi.restoreAllMocks()
callMock.mockReset()
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
process.exitCode = undefined
})
it('prints group help with all computer subcommands', async () => {
@@ -57,21 +58,55 @@ describe('orca computer CLI handlers', () => {
expect(output).toContain('paste-text')
expect(output).toContain('permissions')
expect(output).toContain('set-value')
expect(output).toContain('press-key')
expect(output).toContain('Press a single key such as Return or Escape')
expect(output).not.toContain(['Press a key using', 'xdotool-style syntax'].join(' '))
})
it('passes list-apps through with a resolved worktree', async () => {
queueFixtures(
callMock,
worktreeListFixture([buildWorktree('/tmp/repo', 'feature')]),
okFixture('req_apps', { apps: [] })
it('prints targeted permission setup command help', async () => {
await main(['computer', 'permissions', '--help'], '/tmp/repo')
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).toContain(
'orca computer permissions [--id <accessibility|screenshots>] [--json]'
)
expect(output).toContain('--id <id>')
expect(output).toContain('Identifier for a target item or permission')
})
it('prints command-specific keyboard action help', async () => {
await main(['computer', 'hotkey', '--help'], '/tmp/repo')
const hotkeyOutput = vi.mocked(console.log).mock.calls[0][0]
expect(hotkeyOutput).toContain('--key <key-combo>')
expect(hotkeyOutput).toContain('Modifier chord with one key')
expect(hotkeyOutput).not.toContain('CmdOrCtrl+L')
vi.mocked(console.log).mockClear()
await main(['computer', 'press-key', '--help'], '/tmp/repo')
const pressKeyOutput = vi.mocked(console.log).mock.calls[0][0]
expect(pressKeyOutput).toContain('--key <key>')
expect(pressKeyOutput).toContain('Single key, e.g. Return, Escape, Tab, Left, or PageUp')
})
it('passes list-apps through without resolving a worktree', async () => {
queueFixtures(callMock, okFixture('req_apps', { apps: [] }))
await main(['computer', 'list-apps', '--json'], '/tmp/repo/src')
expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', { limit: 10_000 })
expect(callMock).toHaveBeenNthCalledWith(2, 'computer.listApps', {
worktree: 'id:repo::/tmp/repo'
})
expect(callMock).toHaveBeenCalledTimes(1)
expect(callMock).toHaveBeenCalledWith('computer.listApps', {})
})
it('rejects ignored list-apps worktree scoping before calling the runtime', async () => {
await main(['computer', 'list-apps', '--worktree', 'active'], '/tmp/repo/src')
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain(
'Unknown flag --worktree for command: computer list-apps'
)
expect(process.exitCode).toBe(1)
})
it('prints provider capabilities without resolving a worktree', async () => {
@@ -119,6 +154,33 @@ describe('orca computer CLI handlers', () => {
expect(output).toContain('/Applications/Orca Computer Use.app')
})
it('passes targeted computer permission setup id', async () => {
queueFixtures(
callMock,
okFixture('req_permissions', {
platform: 'darwin',
helperAppPath: '/Applications/Orca Computer Use.app',
openedSettings: true,
launchedHelper: true
})
)
await main(['computer', 'permissions', '--id', 'screenshots'], '/tmp/repo/src')
expect(callMock).toHaveBeenCalledTimes(1)
expect(callMock).toHaveBeenCalledWith('computer.permissions', { id: 'screenshots' })
})
it('rejects invalid computer permission setup id before calling the runtime', async () => {
await main(['computer', 'permissions', '--id', 'screen'], '/tmp/repo/src')
expect(callMock).not.toHaveBeenCalled()
const output = vi.mocked(console.error).mock.calls[0][0]
expect(output).toContain('--id must be "accessibility" or "screenshots"')
expect(output).toContain('Next step: Do not retry the same command unchanged.')
expect(process.exitCode).toBe(1)
})
it('passes get-app-state target and observe flags', async () => {
queueFixtures(
callMock,
@@ -147,10 +209,21 @@ describe('orca computer CLI handlers', () => {
})
})
it('rejects get-app-state without an app before resolving a worktree', async () => {
await main(['computer', 'get-app-state', '--json'], '/tmp/repo/src')
expect(callMock).not.toHaveBeenCalled()
const output = JSON.parse(vi.mocked(console.log).mock.calls[0][0])
expect(output.error).toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Missing required --app')
})
expect(process.exitCode).toBe(1)
})
it('passes list-windows target and formats window IDs', async () => {
queueFixtures(
callMock,
worktreeListFixture([buildWorktree('/tmp/repo', 'feature')]),
okFixture('req_windows', {
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
windows: [
@@ -173,268 +246,18 @@ describe('orca computer CLI handlers', () => {
await main(['computer', 'list-windows', '--app', 'Finder'], '/tmp/repo/src')
expect(callMock).toHaveBeenNthCalledWith(2, 'computer.listWindows', {
app: 'Finder',
worktree: 'id:repo::/tmp/repo'
})
expect(callMock).toHaveBeenCalledTimes(1)
expect(callMock).toHaveBeenCalledWith('computer.listWindows', { app: 'Finder' })
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).toContain('[0] id:42 "Recents"')
})
it('does not resolve worktree when --session is explicit', async () => {
queueFixtures(callMock, okFixture('req_click', sampleSnapshot()))
it('rejects list-windows without an app before calling the runtime', async () => {
await main(['computer', 'list-windows'], '/tmp/repo/src')
await main(
[
'computer',
'click',
'--session',
'manual',
'--app',
'Finder',
'--element-index',
'3',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledTimes(1)
expect(callMock).toHaveBeenCalledWith('computer.click', {
session: 'manual',
app: 'Finder',
elementIndex: 3,
x: undefined,
y: undefined,
clickCount: undefined,
mouseButton: undefined,
noScreenshot: undefined
})
})
it('prints session and window context in action follow-up commands', async () => {
queueFixtures(callMock, okFixture('req_click', sampleSnapshot()))
await main(
[
'computer',
'click',
'--session',
'manual',
'--app',
'Finder',
'--element-index',
'3',
'--window-index',
'1',
'--restore-window'
],
'/tmp/repo/src'
)
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).toContain(
'Use `orca computer get-app-state --app com.apple.finder --session manual --window-index 1 --restore-window`'
)
})
it('maps action command flags to RPC payloads', async () => {
queueFixtures(
callMock,
worktreeListFixture([buildWorktree('/tmp/repo', 'feature')]),
okFixture('req_drag', sampleSnapshot())
)
await main(
[
'computer',
'drag',
'--app',
'Finder',
'--from-x',
'1',
'--from-y',
'2',
'--to-x',
'3',
'--to-y',
'4',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenNthCalledWith(2, 'computer.drag', {
app: 'Finder',
worktree: 'id:repo::/tmp/repo',
fromElementIndex: undefined,
toElementIndex: undefined,
fromX: 1,
fromY: 2,
toX: 3,
toY: 4,
noScreenshot: undefined
})
})
it('maps coordinate scroll flags to RPC payloads', async () => {
queueFixtures(callMock, okFixture('req_scroll', sampleSnapshot()))
await main(
[
'computer',
'scroll',
'--session',
'manual',
'--app',
'Finder',
'--x',
'10',
'--y',
'20',
'--direction',
'down',
'--pages',
'0.5',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.scroll', {
session: 'manual',
app: 'Finder',
elementIndex: undefined,
x: 10,
y: 20,
direction: 'down',
pages: 0.5,
noScreenshot: undefined
})
})
it('maps hotkey and paste-text command flags to RPC payloads', async () => {
queueFixtures(callMock, okFixture('req_hotkey', sampleSnapshot()))
await main(
[
'computer',
'hotkey',
'--session',
'manual',
'--app',
'Finder',
'--key',
'CmdOrCtrl+L',
'--no-screenshot',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.hotkey', {
session: 'manual',
app: 'Finder',
key: 'CmdOrCtrl+L',
noScreenshot: true
})
callMock.mockReset()
vi.mocked(console.log).mockClear()
queueFixtures(callMock, okFixture('req_paste', sampleSnapshot()))
await main(
[
'computer',
'paste-text',
'--session',
'manual',
'--app',
'Finder',
'--text',
'hello world',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.pasteText', {
session: 'manual',
app: 'Finder',
text: 'hello world',
noScreenshot: undefined
})
})
it('formats get-app-state without printing screenshot bytes in pretty mode', async () => {
queueFixtures(callMock, okFixture('req_state', sampleSnapshot()))
await main(['computer', 'get-app-state', '--session', 'manual', '--app', 'Finder'], '/tmp/repo')
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).toContain('Finder (pid 100, com.apple.finder)')
expect(output).toContain('App=com.apple.finder')
expect(output).not.toContain('base64-data')
})
it('omits screenshot bytes from JSON output and writes a screenshot path', async () => {
queueFixtures(callMock, okFixture('req_state', sampleSnapshot()))
await main(
['computer', 'get-app-state', '--session', 'manual', '--app', 'Finder', '--json'],
'/tmp/repo'
)
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).not.toContain('base64-data')
const parsed = JSON.parse(output)
expect(parsed.result.screenshot).toMatchObject({
dataOmitted: true,
format: 'png',
expiresAt: expect.any(String)
})
expect(String(parsed.result.screenshot.path).replaceAll('\\', '/')).toContain(
'orca-computer-use/req_state-screenshot.png'
)
})
it('shows coordinate space and truncation in pretty state output', async () => {
queueFixtures(callMock, okFixture('req_state', sampleSnapshot()))
await main(['computer', 'get-app-state', '--session', 'manual', '--app', 'Finder'], '/tmp/repo')
const output = vi.mocked(console.log).mock.calls[0][0]
expect(output).toContain('Coordinates: window')
expect(output).toContain('Truncated: no')
})
it('passes get-app-state window target flags through', async () => {
queueFixtures(callMock, okFixture('req_snapshot', sampleSnapshot()))
await main(
[
'computer',
'get-app-state',
'--session',
'manual',
'--app',
'Finder',
'--window-id',
'42',
'--window-index',
'0',
'--no-screenshot',
'--json'
],
'/tmp/repo/src'
)
expect(callMock).toHaveBeenCalledWith('computer.getAppState', {
session: 'manual',
app: 'Finder',
noScreenshot: true,
restoreWindow: undefined,
windowId: 42,
windowIndex: 0
})
expect(callMock).not.toHaveBeenCalled()
expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Missing required --app')
expect(process.exitCode).toBe(1)
})
})
@@ -450,13 +273,6 @@ function sampleSnapshot() {
elementCount: 1,
focusedElementId: 0
},
screenshot: {
data: 'base64-data',
format: 'png',
width: 800,
height: 600,
scale: 1
},
screenshotStatus: { state: 'captured' }
}
}
+70 -122
View File
@@ -6,14 +6,8 @@ import type {
ComputerSnapshotResult
} from '../../shared/runtime-types'
import type { CommandHandler } from '../dispatch'
import {
getOptionalNumberFlag,
getOptionalNonNegativeIntegerFlag,
getOptionalPositiveIntegerFlag,
getOptionalStringFlag,
getRequiredStringFlagAllowingEmpty,
getRequiredStringFlag
} from '../flags'
import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { RuntimeClientError } from '../runtime-client'
import {
formatComputerAction,
formatGetAppState,
@@ -21,22 +15,31 @@ import {
formatListWindows,
printResult
} from '../format'
import { RuntimeClientError } from '../runtime-client'
import { getComputerCommandTarget } from '../selectors'
import {
getComputerActionObserveFlags,
getComputerObserveFlags,
getComputerClickActionFlags,
getComputerDragActionFlags,
getComputerHotkeyActionFlags,
getComputerKeyActionFlags,
getComputerScrollActionFlags,
getComputerSecondaryActionFlags,
getComputerSetValueActionFlags,
getComputerTextActionFlags
} from './computer-action-flags'
export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
'computer capabilities': async ({ client, json }) => {
const result = await client.call<ComputerProviderCapabilities>('computer.capabilities', {})
printResult(result, json, formatComputerCapabilities)
},
'computer list-apps': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerListAppsResult>('computer.listApps', {
worktree: target.worktree
})
'computer list-apps': async ({ client, json }) => {
const result = await client.call<ComputerListAppsResult>('computer.listApps', {})
printResult(result, json, formatListApps)
},
'computer permissions': async ({ client, json }) => {
'computer permissions': async ({ flags, client, json }) => {
const id = getComputerPermissionSetupId(flags)
const result = await client.call<{
platform: NodeJS.Platform
helperAppPath: string | null
@@ -44,7 +47,7 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
launchedHelper: boolean
permissions?: { id: string; status: string }[]
nextStep?: string | null
}>('computer.permissions', {})
}>('computer.permissions', id ? { id } : {})
printResult(result, json, (value) => {
if (value.platform !== 'darwin') {
return 'Computer-use permission setup is only required on macOS.'
@@ -67,32 +70,29 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
.join('\n')
})
},
'computer list-windows': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerListWindowsResult>('computer.listWindows', target)
'computer list-windows': async ({ flags, client, json }) => {
const result = await client.call<ComputerListWindowsResult>('computer.listWindows', {
app: getRequiredStringFlag(flags, 'app')
})
printResult(result, json, formatListWindows)
},
'computer get-app-state': async ({ flags, client, cwd, json }) => {
const observeFlags = getComputerObserveFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerSnapshotResult>('computer.getAppState', {
...target,
noScreenshot: flags.has('no-screenshot') ? true : undefined,
restoreWindow: flags.has('restore-window') ? true : undefined,
windowId: getOptionalNumberFlag(flags, 'window-id'),
windowIndex: getOptionalNonNegativeIntegerFlag(flags, 'window-index')
...observeFlags
})
printResult(result, json, formatGetAppState)
},
'computer click': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = getComputerClickActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.click', {
...target,
elementIndex: getOptionalNonNegativeIntegerFlag(flags, 'element-index'),
x: getOptionalNumberFlag(flags, 'x'),
y: getOptionalNumberFlag(flags, 'y'),
clickCount: getOptionalPositiveIntegerFlag(flags, 'click-count'),
mouseButton: getOptionalStringFlag(flags, 'mouse-button'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -100,12 +100,13 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
)
},
'computer perform-secondary-action': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = getComputerSecondaryActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.performSecondaryAction', {
...target,
elementIndex: getRequiredNonNegativeIntegerFlag(flags, 'element-index'),
action: getRequiredStringFlag(flags, 'action'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -113,15 +114,13 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
)
},
'computer scroll': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = getComputerScrollActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.scroll', {
...target,
elementIndex: getOptionalNonNegativeIntegerFlag(flags, 'element-index'),
x: getOptionalNumberFlag(flags, 'x'),
y: getOptionalNumberFlag(flags, 'y'),
direction: getRequiredStringFlag(flags, 'direction'),
pages: getOptionalPositiveNumberFlag(flags, 'pages'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -129,16 +128,13 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
)
},
'computer drag': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = getComputerDragActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.drag', {
...target,
fromElementIndex: getOptionalNonNegativeIntegerFlag(flags, 'from-element-index'),
toElementIndex: getOptionalNonNegativeIntegerFlag(flags, 'to-element-index'),
fromX: getOptionalNumberFlag(flags, 'from-x'),
fromY: getOptionalNumberFlag(flags, 'from-y'),
toX: getOptionalNumberFlag(flags, 'to-x'),
toY: getOptionalNumberFlag(flags, 'to-y'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -146,11 +142,13 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
)
},
'computer type-text': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = await getComputerTextActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.typeText', {
...target,
text: await getTextPayload(flags, 'text'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -158,11 +156,13 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
)
},
'computer press-key': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = getComputerKeyActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.pressKey', {
...target,
key: getRequiredStringFlag(flags, 'key'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -170,11 +170,13 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
)
},
'computer hotkey': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = getComputerHotkeyActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.hotkey', {
...target,
key: getRequiredStringFlag(flags, 'key'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -182,11 +184,13 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
)
},
'computer paste-text': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = await getComputerTextActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.pasteText', {
...target,
text: await getTextPayload(flags, 'text'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -194,12 +198,13 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
)
},
'computer set-value': async ({ flags, client, cwd, json }) => {
const target = await getComputerCommandTarget(flags, cwd, client)
assertComputerAppFlag(flags)
const observeFlags = getComputerActionObserveFlags(flags)
const actionParams = await getComputerSetValueActionFlags(flags)
const target = await getComputerCommandTarget(flags, cwd, client)
const result = await client.call<ComputerActionResult>('computer.setValue', {
...target,
elementIndex: getRequiredNonNegativeIntegerFlag(flags, 'element-index'),
value: await getTextPayload(flags, 'value'),
...actionParams,
...observeFlags
})
printResult(result, json, (value) =>
@@ -208,48 +213,18 @@ export const COMPUTER_HANDLERS: Record<string, CommandHandler> = {
}
}
async function getTextPayload(
flags: Map<string, string | boolean>,
name: 'text' | 'value'
): Promise<string> {
const stdinFlag = `${name}-stdin`
if (flags.has(stdinFlag)) {
if (flags.has(name)) {
throw new RuntimeClientError(
'invalid_argument',
`Use either --${name} or --${stdinFlag}, not both`
)
}
return await readStdin()
}
return name === 'value'
? getRequiredStringFlagAllowingEmpty(flags, name)
: getRequiredStringFlag(flags, name)
function assertComputerAppFlag(flags: Map<string, string | boolean>): void {
getRequiredStringFlag(flags, 'app')
}
async function readStdin(): Promise<string> {
if (process.stdin.isTTY) {
throw new RuntimeClientError('invalid_argument', 'stdin payload requested but stdin is a TTY')
function getComputerPermissionSetupId(
flags: Map<string, string | boolean>
): 'accessibility' | 'screenshots' | undefined {
const id = getOptionalStringFlag(flags, 'id')
if (id === undefined || id === 'accessibility' || id === 'screenshots') {
return id
}
const chunks: Buffer[] = []
for await (const chunk of process.stdin) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
}
return Buffer.concat(chunks).toString('utf8')
}
function getOptionalPositiveNumberFlag(
flags: Map<string, string | boolean>,
name: string
): number | undefined {
const value = getOptionalNumberFlag(flags, name)
if (value === undefined) {
return undefined
}
if (value <= 0) {
throw new RuntimeClientError('invalid_argument', `Invalid positive number for --${name}`)
}
return value
throw new RuntimeClientError('invalid_argument', '--id must be "accessibility" or "screenshots"')
}
function formatComputerCapabilities(value: ComputerProviderCapabilities): string {
@@ -264,30 +239,3 @@ function formatComputerCapabilities(value: ComputerProviderCapabilities): string
.join(', ')}`
].join('\n')
}
function getRequiredNonNegativeIntegerFlag(
flags: Map<string, string | boolean>,
name: string
): number {
const value = getOptionalNonNegativeIntegerFlag(flags, name)
if (value === undefined) {
throw new RuntimeClientError('invalid_argument', `Missing required --${name}`)
}
return value
}
function getComputerActionObserveFlags(flags: Map<string, string | boolean>): {
noScreenshot?: boolean
restoreWindow?: boolean
windowId?: number
windowIndex?: number
} {
const windowId = getOptionalNumberFlag(flags, 'window-id')
const windowIndex = getOptionalNonNegativeIntegerFlag(flags, 'window-index')
return {
noScreenshot: flags.has('no-screenshot') ? true : undefined,
...(flags.has('restore-window') ? { restoreWindow: true } : {}),
...(windowId !== undefined ? { windowId } : {}),
...(windowIndex !== undefined ? { windowIndex } : {})
}
}
+17 -4
View File
@@ -82,7 +82,8 @@ Orchestration:
orchestration reset Reset orchestration state
Computer Use:
computer permissions Open the macOS permission setup for computer-use
computer capabilities Show computer-use provider capabilities
computer permissions Show or open computer-use permission setup
computer list-apps List running apps available to computer-use
computer list-windows List visible windows for a target app
computer get-app-state Capture a compact accessibility snapshot of an app
@@ -91,7 +92,7 @@ Computer Use:
computer scroll Scroll an app element
computer drag Drag between app elements or window coordinates
computer type-text Type literal text at the current app focus
computer press-key Press a key using xdotool-style syntax
computer press-key Press a single key such as Return or Escape
computer hotkey Press a shortcut combination such as CmdOrCtrl+A
computer paste-text Paste text through the native clipboard path
computer set-value Set the value of a settable app element
@@ -311,7 +312,7 @@ export function formatCommandHelp(spec: CommandSpec): string {
if (displayedFlags.length > 0) {
lines.push('', 'Options:')
for (const flag of displayedFlags) {
lines.push(` ${formatFlagHelp(flag)}`)
lines.push(` ${formatCommandFlagHelp(flag, spec.path)}`)
}
}
@@ -342,6 +343,17 @@ export function formatGroupHelp(specs: CommandSpec[], group: string): string {
return lines.join('\n')
}
function formatCommandFlagHelp(flag: string, commandPath: string[]): string {
const command = commandPath.join(' ')
if (flag === 'key' && command === 'computer hotkey') {
return '--key <key-combo> Modifier chord with one key, e.g. CmdOrCtrl+A'
}
if (flag === 'key' && command === 'computer press-key') {
return '--key <key> Single key, e.g. Return, Escape, Tab, Left, or PageUp'
}
return formatFlagHelp(flag)
}
export function formatFlagHelp(flag: string): string {
const helpByFlag: Record<string, string> = {
agent: '--agent <id> Launch a known TUI agent in the first terminal',
@@ -366,9 +378,10 @@ export function formatFlagHelp(flag: string): string {
'from-y': '--from-y <y> Source window-local y coordinate',
help: '--help Show this help message',
interrupt: '--interrupt Send as an interrupt-style input when supported',
id: '--id <id> Identifier for a target item or permission',
issue: '--issue <number|null> Linked GitHub issue number',
json: '--json Emit machine-readable JSON',
key: '--key <key> Key or combo to press, e.g. Escape or CmdOrCtrl+L',
key: '--key <key> Key argument for this command',
limit: '--limit <n> Maximum number of rows to return',
mode: '--mode <mode> Mode such as edit, diff, or both',
'mouse-button': '--mouse-button <btn> Mouse button: left, right, or middle',
+19
View File
@@ -113,6 +113,25 @@ describe('COMMAND_SPECS collision check', () => {
})
})
describe('orca root help', () => {
it('advertises computer-use capabilities discovery', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
await main(['--help'], '/tmp/repo')
expect(logSpy.mock.calls[0][0]).toContain(
'computer capabilities Show computer-use provider capabilities'
)
expect(logSpy.mock.calls[0][0]).toContain(
'computer permissions Show or open computer-use permission setup'
)
expect(logSpy.mock.calls[0][0]).toContain(
'computer press-key Press a single key such as Return or Escape'
)
expect(callMock).not.toHaveBeenCalled()
})
})
describe('orca cli worktree awareness', () => {
const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE
const originalUserDataPath = process.env.ORCA_USER_DATA_PATH
+1 -1
View File
@@ -71,7 +71,7 @@ export async function main(argv = process.argv.slice(2), cwd = process.cwd()): P
json
})
} catch (error) {
reportCliError(error, json)
reportCliError(error, json, { commandPath: parsed.commandPath })
process.exitCode = 1
}
}
+17
View File
@@ -22,6 +22,23 @@ describe('RuntimeRpcEnvelopeSchema', () => {
expect(parsed.success).toBe(true)
})
it('accepts structured failure data for agent recovery hints', () => {
const parsed = RuntimeRpcEnvelopeSchema.safeParse({
id: 'req-1',
ok: false,
error: {
code: 'app_not_found',
message: 'app not found: Gmail',
data: {
nextSteps: ['Target the desktop browser app/window that contains Gmail.']
}
},
_meta: { runtimeId: 'runtime-1' }
})
expect(parsed.success).toBe(true)
})
it('accepts a failure envelope without _meta', () => {
// Why: the runtime may fail before it has resolved its own runtimeId, in
// which case _meta is omitted. The schema must tolerate that rather than
+9 -2
View File
@@ -17,7 +17,7 @@ export type BrowserCliTarget = {
export type ComputerCliTarget = {
session?: string
worktree?: string
app?: ComputerAppQuery
app: ComputerAppQuery
}
export function buildCurrentWorktreeSelector(cwd: string): string {
@@ -198,8 +198,15 @@ export async function getComputerCommandTarget(
cwd: string,
client: RuntimeClient
): Promise<ComputerCliTarget> {
const app = getOptionalStringFlag(flags, 'app')
const app = getRequiredStringFlag(flags, 'app')
const session = getOptionalStringFlag(flags, 'session')
const worktree = getOptionalStringFlag(flags, 'worktree')
if (session && worktree) {
throw new RuntimeClientError(
'invalid_argument',
'Computer-use targeting accepts either --session or --worktree, not both'
)
}
if (session) {
return { session, app }
}
+20
View File
@@ -0,0 +1,20 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { quoteCliCommandArgument } from './shell-command-quote'
describe('quoteCliCommandArgument', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('leaves simple selectors unquoted', () => {
expect(quoteCliCommandArgument('com.apple.finder')).toBe('com.apple.finder')
})
it('quotes values with spaces for the current platform shell', () => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')
expect(quoteCliCommandArgument('Text Editor')).toBe("'Text Editor'")
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
expect(quoteCliCommandArgument('Text Editor')).toBe('"Text Editor"')
})
})
+9
View File
@@ -0,0 +1,9 @@
export function quoteCliCommandArgument(value: string): string {
if (/^[a-zA-Z0-9._:/@-]+$/.test(value)) {
return value
}
if (process.platform === 'win32') {
return `"${value.replace(/"/g, '\\"')}"`
}
return `'${value.replaceAll("'", "'\\''")}'`
}
+34
View File
@@ -3,6 +3,22 @@ import { describe, expect, it } from 'vitest'
import { COMPUTER_COMMAND_SPECS } from './computer'
describe('computer command specs', () => {
it('does not advertise ignored worktree/session scoping for app and window listing', () => {
const listApps = COMPUTER_COMMAND_SPECS.find(
(spec) => spec.path.join(' ') === 'computer list-apps'
)
const listWindows = COMPUTER_COMMAND_SPECS.find(
(spec) => spec.path.join(' ') === 'computer list-windows'
)
expect(listApps?.allowedFlags).not.toContain('worktree')
expect(listApps?.usage).not.toContain('worktree')
expect(listWindows?.allowedFlags).not.toContain('worktree')
expect(listWindows?.allowedFlags).not.toContain('session')
expect(listWindows?.usage).not.toContain('worktree')
expect(listWindows?.usage).not.toContain('session')
})
it('allows explicit window targeting on action commands', () => {
const actionSpecs = COMPUTER_COMMAND_SPECS.filter((spec) =>
[
@@ -23,4 +39,22 @@ describe('computer command specs', () => {
expect(spec.allowedFlags).toEqual(expect.arrayContaining(['window-id', 'window-index']))
}
})
it('advertises press-key as a single-key command', () => {
const pressKey = COMPUTER_COMMAND_SPECS.find(
(spec) => spec.path.join(' ') === 'computer press-key'
)
expect(pressKey?.summary).toContain('Press a single key')
expect(pressKey?.summary).not.toContain('xdotool')
})
it('advertises targeted computer-use permission setup', () => {
const permissions = COMPUTER_COMMAND_SPECS.find(
(spec) => spec.path.join(' ') === 'computer permissions'
)
expect(permissions?.allowedFlags).toContain('id')
expect(permissions?.usage).toContain('--id <accessibility|screenshots>')
})
})
+7 -8
View File
@@ -20,21 +20,20 @@ export const COMPUTER_COMMAND_SPECS: CommandSpec[] = [
{
path: ['computer', 'list-apps'],
summary: 'List running apps available to computer-use',
usage: 'orca computer list-apps [--worktree <selector>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'worktree']
usage: 'orca computer list-apps [--json]',
allowedFlags: [...GLOBAL_FLAGS]
},
{
path: ['computer', 'permissions'],
summary: 'Open computer-use permission setup',
usage: 'orca computer permissions [--json]',
allowedFlags: [...GLOBAL_FLAGS]
usage: 'orca computer permissions [--id <accessibility|screenshots>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'id']
},
{
path: ['computer', 'list-windows'],
summary: 'List windows for an app available to computer-use',
usage:
'orca computer list-windows --app <name|bundle|pid:N> [--worktree <selector> | --session <id>] [--json]',
allowedFlags: COMPUTER_FLAGS
usage: 'orca computer list-windows --app <name|bundle|pid:N> [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'app']
},
{
path: ['computer', 'get-app-state'],
@@ -95,7 +94,7 @@ export const COMPUTER_COMMAND_SPECS: CommandSpec[] = [
},
{
path: ['computer', 'press-key'],
summary: 'Press a key using xdotool-style syntax',
summary: 'Press a single key such as Return or Escape',
usage:
'orca computer press-key --app <app> --key <key> [--window-id <id> | --window-index <n>] [--restore-window] [--no-screenshot] [--json]',
allowedFlags: [...COMPUTER_ACTION_FLAGS, 'key']
+126
View File
@@ -0,0 +1,126 @@
import type {
RuntimeTerminalClose,
RuntimeTerminalCreate,
RuntimeTerminalFocus,
RuntimeTerminalListResult,
RuntimeTerminalRead,
RuntimeTerminalRename,
RuntimeTerminalSend,
RuntimeTerminalShow,
RuntimeTerminalSplit,
RuntimeTerminalWait
} from '../shared/runtime-types'
export function formatTerminalList(result: RuntimeTerminalListResult): string {
if (result.terminals.length === 0) {
return 'No live terminals.'
}
const body = result.terminals
.map(
(terminal) =>
`${terminal.handle} ${terminal.title ?? '(untitled)'} ${terminal.connected ? 'connected' : 'disconnected'} ${terminal.worktreePath}\n${terminal.preview ? `preview: ${terminal.preview}` : 'preview: <empty>'}`
)
.join('\n\n')
return result.truncated
? `${body}\n\ntruncated: showing ${result.terminals.length} of ${result.totalCount}`
: body
}
export function formatTerminalShow(result: { terminal: RuntimeTerminalShow }): string {
const terminal = result.terminal
return [
`handle: ${terminal.handle}`,
`title: ${terminal.title ?? '(untitled)'}`,
`worktree: ${terminal.worktreePath}`,
`branch: ${terminal.branch}`,
`leaf: ${terminal.leafId}`,
`ptyId: ${terminal.ptyId ?? 'none'}`,
`connected: ${terminal.connected}`,
`writable: ${terminal.writable}`,
`preview: ${terminal.preview || '<empty>'}`
].join('\n')
}
export function formatTerminalRead(result: { terminal: RuntimeTerminalRead }): string {
const terminal = result.terminal
const oldestCursor =
typeof terminal.oldestCursor === 'string' ? [`oldest cursor: ${terminal.oldestCursor}`] : []
const latestCursor =
typeof terminal.latestCursor === 'string' ? [`latest cursor: ${terminal.latestCursor}`] : []
const limitedWarning = formatTerminalReadLimitedWarning(terminal)
const header = [
`handle: ${terminal.handle}`,
`status: ${terminal.status}`,
...(terminal.nextCursor !== null ? [`cursor: ${terminal.nextCursor}`] : []),
...oldestCursor,
...latestCursor,
...(terminal.truncated ? ['warning: older output is no longer retained'] : []),
...(limitedWarning ? [limitedWarning] : [])
]
return [...header, '', ...terminal.tail].join('\n')
}
function formatTerminalReadLimitedWarning(terminal: RuntimeTerminalRead): string | null {
if (!terminal.limited) {
return null
}
if (
typeof terminal.nextCursor === 'string' &&
typeof terminal.latestCursor === 'string' &&
terminal.nextCursor !== terminal.latestCursor
) {
return `warning: output limited; continue with --cursor ${terminal.nextCursor}`
}
if (
typeof terminal.oldestCursor === 'string' &&
typeof terminal.latestCursor === 'string' &&
terminal.oldestCursor !== terminal.latestCursor
) {
// A tail preview's next cursor is already latest, so oldestCursor is the retained history entry point.
return `warning: output limited; page retained output with --cursor ${terminal.oldestCursor} --limit <count>`
}
return 'warning: output limited'
}
export function formatTerminalSend(result: { send: RuntimeTerminalSend }): string {
return `Sent ${result.send.bytesWritten} bytes to ${result.send.handle}.`
}
export function formatTerminalRename(result: { rename: RuntimeTerminalRename }): string {
return result.rename.title
? `Renamed terminal ${result.rename.handle} to "${result.rename.title}".`
: `Cleared title for terminal ${result.rename.handle}.`
}
export function formatTerminalCreate(result: { terminal: RuntimeTerminalCreate }): string {
const titleNote = result.terminal.title ? ` (title: "${result.terminal.title}")` : ''
const surfaceNote = result.terminal.surface ? ` [${result.terminal.surface}]` : ''
return `Created terminal ${result.terminal.handle}${titleNote}${surfaceNote}`
}
export function formatTerminalSplit(result: { split: RuntimeTerminalSplit }): string {
return `Split pane ${result.split.handle} in tab ${result.split.tabId}`
}
export function formatTerminalFocus(result: { focus: RuntimeTerminalFocus }): string {
return `Focused terminal ${result.focus.handle} (tab ${result.focus.tabId}).`
}
export function formatTerminalClose(result: { close: RuntimeTerminalClose }): string {
const ptyNote = result.close.ptyKilled ? ' PTY killed.' : ''
return `Closed terminal ${result.close.handle}.${ptyNote}`
}
export function formatTerminalWait(result: { wait: RuntimeTerminalWait }): string {
const lines = [
`handle: ${result.wait.handle}`,
`condition: ${result.wait.condition}`,
`satisfied: ${result.wait.satisfied}`,
`status: ${result.wait.status}`,
`exitCode: ${result.wait.exitCode ?? 'null'}`
]
if (result.wait.blockedReason) {
lines.push(`blockedReason: ${result.wait.blockedReason}`)
}
return lines.join('\n')
}
+250
View File
@@ -0,0 +1,250 @@
import type { Automation, AutomationRun } from '../shared/automations-types'
import { formatAutomationPrecheckTimeout } from '../shared/automation-precheck'
import { formatAutomationSchedule } from '../shared/automation-schedules'
import type { PublicKnownRuntimeEnvironment } from '../shared/runtime-environments'
import type {
RuntimeRepoList,
RuntimeRepoSearchRefs,
RuntimeWorktreeListResult,
RuntimeWorktreePsResult,
RuntimeWorktreeRecord
} from '../shared/runtime-types'
import type { MemorySnapshot, WorktreeMemory } from '../shared/types'
export function formatMemorySnapshot(snapshot: MemorySnapshot): string {
const topWorktrees = [...snapshot.worktrees].sort((a, b) => b.memory - a.memory).slice(0, 10)
const lines = [
`collectedAt: ${new Date(snapshot.collectedAt).toISOString()}`,
`totalMemory: ${formatByteCount(snapshot.totalMemory)}`,
`totalCpu: ${formatCpu(snapshot.totalCpu)}`,
[
`hostUsed: ${formatByteCount(snapshot.host.usedMemory)}`,
`/ ${formatByteCount(snapshot.host.totalMemory)}`,
`(${snapshot.host.memoryUsagePercent.toFixed(1)}%)`
].join(' '),
[
`app: ${formatByteCount(snapshot.app.memory)}`,
`(main ${formatByteCount(snapshot.app.main.memory)},`,
`renderer ${formatByteCount(snapshot.app.renderer.memory)},`,
`other ${formatByteCount(snapshot.app.other.memory)})`
].join(' '),
`worktrees: ${snapshot.worktrees.length}`
]
if (topWorktrees.length === 0) {
lines.push('topWorktrees: none')
return lines.join('\n')
}
lines.push('', 'Top worktrees:')
for (const worktree of topWorktrees) {
lines.push(formatWorktreeMemoryLine(worktree))
}
if (snapshot.worktrees.length > topWorktrees.length) {
lines.push(`... ${snapshot.worktrees.length - topWorktrees.length} more worktrees`)
}
return lines.join('\n')
}
function formatWorktreeMemoryLine(worktree: WorktreeMemory): string {
return [
`- ${worktree.worktreeName}`,
`${formatByteCount(worktree.memory)}`,
`${formatCpu(worktree.cpu)}`,
`${worktree.sessions.length} session${worktree.sessions.length === 1 ? '' : 's'}`
].join(' ')
}
function formatCpu(cpu: number): string {
return `${cpu.toFixed(1)}%`
}
function formatByteCount(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) {
return '0 B'
}
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let value = bytes
let unitIndex = 0
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024
unitIndex += 1
}
const formatted = value >= 10 || unitIndex === 0 ? value.toFixed(0) : value.toFixed(1)
return `${formatted} ${units[unitIndex]}`
}
export function formatEnvironmentList(result: {
environments: PublicKnownRuntimeEnvironment[]
}): string {
if (result.environments.length === 0) {
return 'No saved environments.'
}
return result.environments
.map(
(environment) =>
`${environment.id} ${environment.name} ${environment.endpoints[0]?.endpoint ?? 'no-endpoint'}`
)
.join('\n')
}
export function formatEnvironment(environment: PublicKnownRuntimeEnvironment): string {
return [
`id: ${environment.id}`,
`name: ${environment.name}`,
`runtimeId: ${environment.runtimeId ?? 'unknown'}`,
`lastUsedAt: ${environment.lastUsedAt ?? 'never'}`,
`preferredEndpointId: ${environment.preferredEndpointId}`,
...environment.endpoints.map(
(endpoint) => `endpoint: ${endpoint.id} ${endpoint.kind} ${endpoint.endpoint}`
)
].join('\n')
}
export function formatWorktreePs(result: RuntimeWorktreePsResult): string {
if (result.worktrees.length === 0) {
return 'No worktrees found.'
}
const body = result.worktrees
.map(
(worktree) =>
`${worktree.repo} ${worktree.branch} live:${worktree.liveTerminalCount} pty:${worktree.hasAttachedPty ? 'yes' : 'no'} unread:${worktree.unread ? 'yes' : 'no'}\n${worktree.path}${worktree.preview ? `\npreview: ${worktree.preview}` : ''}`
)
.join('\n\n')
return result.truncated
? `${body}\n\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: body
}
export function formatRepoList(result: RuntimeRepoList): string {
if (result.repos.length === 0) {
return 'No repos found.'
}
return result.repos.map((repo) => `${repo.id} ${repo.displayName} ${repo.path}`).join('\n')
}
export function formatRepoShow(result: { repo: Record<string, unknown> }): string {
return Object.entries(result.repo)
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
}
export function formatRepoRefs(result: RuntimeRepoSearchRefs): string {
if (result.refs.length === 0) {
return 'No refs found.'
}
return result.truncated ? `${result.refs.join('\n')}\n\ntruncated: yes` : result.refs.join('\n')
}
export function formatWorktreeList(result: RuntimeWorktreeListResult): string {
if (result.worktrees.length === 0) {
return 'No worktrees found.'
}
const body = result.worktrees
.map((worktree) => {
const childCount = worktree.childWorktreeIds?.length ?? 0
return `${String(worktree.id)} ${String(worktree.branch)} ${String(worktree.path)}\ndisplayName: ${String(worktree.displayName ?? '')}\nparentWorktreeId: ${String(worktree.parentWorktreeId ?? 'null')}\nchildWorktreeIds: ${childCount > 0 ? worktree.childWorktreeIds.join(',') : '[]'}\nlinkedIssue: ${String(worktree.linkedIssue ?? 'null')}\ncomment: ${String(worktree.comment ?? '')}`
})
.join('\n\n')
return result.truncated
? `${body}\n\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: body
}
export function formatWorktreeShow(result: { worktree: RuntimeWorktreeRecord }): string {
const worktree = result.worktree
return Object.entries(worktree)
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
}
export function formatAutomationList(result: { automations: Automation[] }): string {
if (result.automations.length === 0) {
return 'No automations found.'
}
return result.automations
.map((automation) => {
const status = automation.enabled ? 'enabled' : 'disabled'
return `${automation.id} ${automation.name} ${automation.agentId} ${status}\n${formatAutomationSchedule(automation.rrule)} next: ${new Date(automation.nextRunAt).toISOString()}`
})
.join('\n\n')
}
export function formatAutomationShow(result: { automation: Automation }): string {
const automation = result.automation
return [
`id: ${automation.id}`,
`name: ${automation.name}`,
`provider: ${automation.agentId}`,
`enabled: ${automation.enabled}`,
`schedule: ${formatAutomationSchedule(automation.rrule)}`,
`rrule: ${automation.rrule}`,
`precheck: ${
automation.precheck
? `${automation.precheck.command} (timeout ${formatAutomationPrecheckTimeout(
automation.precheck.timeoutSeconds
)})`
: 'none'
}`,
`nextRunAt: ${new Date(automation.nextRunAt).toISOString()}`,
`projectId: ${automation.projectId}`,
`workspaceMode: ${automation.workspaceMode}`,
`workspaceId: ${automation.workspaceId ?? 'null'}`,
`baseBranch: ${automation.baseBranch ?? 'null'}`,
`reuseSession: ${automation.reuseSession}`,
`target: ${automation.executionTargetType}:${automation.executionTargetId}`,
`prompt: ${automation.prompt}`
].join('\n')
}
export function formatAutomationRemoved(result: { removed: boolean; id: string }): string {
return result.removed
? `Removed automation ${result.id}.`
: `Automation ${result.id} not removed.`
}
export function formatAutomationRun(result: { run: AutomationRun }): string {
return [
`id: ${result.run.id}`,
`automationId: ${result.run.automationId}`,
`title: ${result.run.title}`,
`status: ${result.run.status}`,
`trigger: ${result.run.trigger}`,
`scheduledFor: ${new Date(result.run.scheduledFor).toISOString()}`,
`workspaceId: ${result.run.workspaceId ?? 'null'}`,
`precheck: ${formatAutomationRunPrecheck(result.run)}`,
`error: ${result.run.error ?? 'null'}`
].join('\n')
}
function formatAutomationRunPrecheck(run: AutomationRun): string {
const result = run.precheckResult
if (!result) {
return 'none'
}
const outcome = result.timedOut
? 'timed out'
: result.error
? 'error'
: `exit ${result.exitCode ?? 'unknown'}`
const output = result.stderr.trim() || result.stdout.trim()
return output ? `${outcome}; ${output}` : outcome
}
export function formatAutomationRuns(result: { runs: AutomationRun[] }): string {
if (result.runs.length === 0) {
return 'No automation runs found.'
}
return result.runs
.map(
(run) =>
`${run.id} ${run.automationId} ${run.status} ${run.trigger} ${new Date(run.scheduledFor).toISOString()}\n${run.title}${run.precheckResult ? `\nprecheck: ${formatAutomationRunPrecheck(run)}` : ''}${run.error ? `\nerror: ${run.error}` : ''}`
)
.join('\n\n')
}
@@ -0,0 +1,24 @@
import type { ComputerActionResult } from '../../shared/runtime-types'
export function normalizeComputerActionResult(result: ComputerActionResult): ComputerActionResult {
const action = result.action
if (!action) {
return result
}
const verificationReason =
action.path === 'synthetic'
? ('synthetic_input' as const)
: action.path === 'clipboard'
? ('clipboard_paste' as const)
: null
if (!verificationReason || action.verification) {
return result
}
return {
...result,
action: {
...action,
verification: { state: 'unverified', reason: verificationReason }
}
}
}
@@ -0,0 +1,238 @@
import {
computerUseHotkeyValidationMessage,
computerUsePressKeyValidationMessage
} from '../../shared/computer-use-key-spec'
import { RuntimeClientError } from './runtime-client-error'
type ComputerProviderActionMethod =
| 'click'
| 'performSecondaryAction'
| 'scroll'
| 'drag'
| 'typeText'
| 'pressKey'
| 'hotkey'
| 'pasteText'
| 'setValue'
export function validateComputerProviderActionParams(
method: ComputerProviderActionMethod,
params: Record<string, unknown>
): string {
const app = requireNonEmptyString(params, 'app')
validateWindowTarget(params)
switch (method) {
case 'click':
validateElementOrCoordinates('Click', params)
validatePositiveInteger(params, 'clickCount')
validateMouseButton(params)
return app
case 'performSecondaryAction':
requireNonNegativeInteger(params, 'elementIndex')
requireNonEmptyString(params, 'action')
return app
case 'scroll':
validateElementOrCoordinates('Scroll', params)
validateScrollDirection(params)
validatePositiveNumber(params, 'pages')
return app
case 'drag':
validateDragTarget(params)
return app
case 'typeText':
case 'pasteText':
requireNonEmptyString(params, 'text')
return app
case 'pressKey':
validatePressKey(params)
return app
case 'hotkey':
validateHotkey(params)
return app
case 'setValue':
requireNonNegativeInteger(params, 'elementIndex')
requireStringAllowingEmpty(params, 'value')
return app
}
}
function validateWindowTarget(params: Record<string, unknown>): void {
if (params.windowId !== undefined && params.windowIndex !== undefined) {
throw new RuntimeClientError(
'invalid_argument',
'Window targeting accepts either windowId or windowIndex, not both'
)
}
}
function validateElementOrCoordinates(
actionName: 'Click' | 'Scroll',
params: Record<string, unknown>
): void {
const hasElement = params.elementIndex !== undefined
const hasX = params.x !== undefined
const hasY = params.y !== undefined
if (!hasElement && !(hasX && hasY)) {
throw new RuntimeClientError(
'invalid_argument',
`${actionName} requires elementIndex or both x and y`
)
}
if (hasX !== hasY) {
throw new RuntimeClientError(
'invalid_argument',
`${actionName} coordinates require both x and y`
)
}
if (hasElement && (hasX || hasY)) {
throw new RuntimeClientError(
'invalid_argument',
`${actionName} accepts either elementIndex or coordinate fields, not both`
)
}
if (params.elementIndex !== undefined) {
requireNonNegativeInteger(params, 'elementIndex')
}
requireFiniteNumber(params, 'x')
requireFiniteNumber(params, 'y')
}
function validateDragTarget(params: Record<string, unknown>): void {
const hasElementPair =
params.fromElementIndex !== undefined && params.toElementIndex !== undefined
const hasPartialElementPair =
params.fromElementIndex !== undefined || params.toElementIndex !== undefined
const coordinates = [params.fromX, params.fromY, params.toX, params.toY]
const hasCoordinatePair = coordinates.every((coordinate) => coordinate !== undefined)
const hasPartialCoordinatePair = coordinates.some((coordinate) => coordinate !== undefined)
if (hasElementPair && hasCoordinatePair) {
throw new RuntimeClientError(
'invalid_argument',
'Drag accepts either element indexes or coordinate fields, not both'
)
}
if (hasPartialElementPair && !hasElementPair) {
throw new RuntimeClientError(
'invalid_argument',
'Drag element targeting requires both fromElementIndex and toElementIndex'
)
}
if (hasPartialCoordinatePair && !hasCoordinatePair) {
throw new RuntimeClientError(
'invalid_argument',
'Drag coordinates require fromX, fromY, toX, and toY'
)
}
if (!hasElementPair && !hasCoordinatePair) {
throw new RuntimeClientError(
'invalid_argument',
'Drag requires fromElementIndex and toElementIndex, or all coordinate fields'
)
}
if (hasElementPair) {
requireNonNegativeInteger(params, 'fromElementIndex')
requireNonNegativeInteger(params, 'toElementIndex')
}
if (hasCoordinatePair) {
requireFiniteNumber(params, 'fromX')
requireFiniteNumber(params, 'fromY')
requireFiniteNumber(params, 'toX')
requireFiniteNumber(params, 'toY')
}
}
function validateMouseButton(params: Record<string, unknown>): void {
const mouseButton = params.mouseButton
if (
mouseButton !== undefined &&
mouseButton !== 'left' &&
mouseButton !== 'right' &&
mouseButton !== 'middle'
) {
throw new RuntimeClientError(
'invalid_argument',
'Unsupported mouseButton; expected left, right, or middle'
)
}
}
function validateScrollDirection(params: Record<string, unknown>): void {
const direction = requireNonEmptyString(params, 'direction')
if (direction !== 'up' && direction !== 'down' && direction !== 'left' && direction !== 'right') {
throw new RuntimeClientError(
'invalid_argument',
'Unsupported direction; expected up, down, left, or right'
)
}
}
function validatePressKey(params: Record<string, unknown>): void {
const key = requireNonEmptyString(params, 'key')
const message = computerUsePressKeyValidationMessage(key)
if (message) {
throw new RuntimeClientError('invalid_argument', message)
}
}
function validateHotkey(params: Record<string, unknown>): void {
const key = requireNonEmptyString(params, 'key')
const message = computerUseHotkeyValidationMessage(key)
if (message) {
throw new RuntimeClientError('invalid_argument', message)
}
}
function requireStringAllowingEmpty(params: Record<string, unknown>, key: string): string {
const value = params[key]
if (typeof value !== 'string') {
throw new RuntimeClientError('invalid_argument', `Missing ${key}`)
}
return value
}
function requireNonEmptyString(params: Record<string, unknown>, key: string): string {
const value = requireStringAllowingEmpty(params, key)
if (value.length === 0) {
throw new RuntimeClientError('invalid_argument', `Missing ${key}`)
}
return value
}
function requireNonNegativeInteger(params: Record<string, unknown>, key: string): number {
const value = params[key]
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {
throw new RuntimeClientError('invalid_argument', `${key} must be a non-negative integer`)
}
return value
}
function requireFiniteNumber(params: Record<string, unknown>, key: string): number | undefined {
const value = params[key]
if (value === undefined) {
return undefined
}
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new RuntimeClientError('invalid_argument', `${key} must be a finite number`)
}
return value
}
function validatePositiveInteger(params: Record<string, unknown>, key: string): void {
const value = params[key]
if (value === undefined) {
return
}
if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
throw new RuntimeClientError('invalid_argument', `${key} must be a positive integer`)
}
}
function validatePositiveNumber(params: Record<string, unknown>, key: string): void {
const value = params[key]
if (value === undefined) {
return
}
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
throw new RuntimeClientError('invalid_argument', `${key} must be a positive number`)
}
}
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from 'vitest'
import { ComputerProviderLifecycle } from './computer-provider-lifecycle'
function provider(name: string) {
return {
name,
capabilities: vi.fn(),
listApps: vi.fn(),
listWindows: vi.fn(),
snapshot: vi.fn(),
action: vi.fn(),
shutdown: vi.fn()
}
}
describe('ComputerProviderLifecycle', () => {
it('rechecks macOS provider availability after an initial miss', () => {
const macProvider = provider('mac')
const shouldUseMacOSNativeProvider = vi.fn().mockReturnValueOnce(false).mockReturnValue(true)
const lifecycle = new ComputerProviderLifecycle({
shouldUseMacOSNativeProvider,
createMacOSNativeProvider: vi.fn(() => macProvider as never),
shouldUseDesktopScriptProvider: vi.fn(() => false),
createDesktopScriptProvider: vi.fn()
})
expect(lifecycle.current('darwin')).toBeNull()
expect(lifecycle.current('darwin')).toBe(macProvider)
expect(shouldUseMacOSNativeProvider).toHaveBeenCalledTimes(2)
})
it('caches an available provider and shuts it down', () => {
const macProvider = provider('mac')
const createMacOSNativeProvider = vi.fn(() => macProvider as never)
const lifecycle = new ComputerProviderLifecycle({
shouldUseMacOSNativeProvider: vi.fn(() => true),
createMacOSNativeProvider,
shouldUseDesktopScriptProvider: vi.fn(() => false),
createDesktopScriptProvider: vi.fn()
})
expect(lifecycle.current('darwin')).toBe(macProvider)
expect(lifecycle.current('darwin')).toBe(macProvider)
expect(createMacOSNativeProvider).toHaveBeenCalledTimes(1)
lifecycle.shutdown()
expect(macProvider.shutdown).toHaveBeenCalledTimes(1)
})
it('uses the desktop script provider on Linux when available', () => {
const desktopProvider = provider('desktop')
const lifecycle = new ComputerProviderLifecycle({
shouldUseMacOSNativeProvider: vi.fn(() => false),
createMacOSNativeProvider: vi.fn(),
shouldUseDesktopScriptProvider: vi.fn(() => true),
createDesktopScriptProvider: vi.fn(() => desktopProvider as never)
})
expect(lifecycle.current('linux')).toBe(desktopProvider)
})
it('shuts down the desktop script provider', () => {
const desktopProvider = provider('desktop')
const lifecycle = new ComputerProviderLifecycle({
shouldUseMacOSNativeProvider: vi.fn(() => false),
createMacOSNativeProvider: vi.fn(),
shouldUseDesktopScriptProvider: vi.fn(() => true),
createDesktopScriptProvider: vi.fn(() => desktopProvider as never)
})
expect(lifecycle.current('linux')).toBe(desktopProvider)
lifecycle.shutdown()
expect(desktopProvider.shutdown).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,67 @@
import { MacOSNativeProviderClient } from './macos-native-provider-client'
import { shouldUseMacOSNativeProvider } from './macos-native-provider-availability'
import {
DesktopScriptProviderClient,
shouldUseDesktopScriptProvider
} from './desktop-script-provider-client'
type ComputerProvider = MacOSNativeProviderClient | DesktopScriptProviderClient
type ComputerProviderLifecycleDeps = {
shouldUseMacOSNativeProvider: () => boolean
createMacOSNativeProvider: () => MacOSNativeProviderClient
shouldUseDesktopScriptProvider: () => boolean
createDesktopScriptProvider: () => DesktopScriptProviderClient
}
const defaultDeps: ComputerProviderLifecycleDeps = {
shouldUseMacOSNativeProvider,
createMacOSNativeProvider: () => new MacOSNativeProviderClient(),
shouldUseDesktopScriptProvider,
createDesktopScriptProvider: () => new DesktopScriptProviderClient()
}
export class ComputerProviderLifecycle {
private nativeMacOSProvider: MacOSNativeProviderClient | null = null
private desktopScriptProvider: DesktopScriptProviderClient | null = null
constructor(private readonly deps: ComputerProviderLifecycleDeps = defaultDeps) {}
current(platform: NodeJS.Platform = process.platform): ComputerProvider | null {
if (platform === 'darwin') {
if (this.nativeMacOSProvider) {
return this.nativeMacOSProvider
}
if (this.deps.shouldUseMacOSNativeProvider()) {
this.nativeMacOSProvider = this.deps.createMacOSNativeProvider()
return this.nativeMacOSProvider
}
}
if (this.desktopScriptProvider) {
return this.desktopScriptProvider
}
if (this.deps.shouldUseDesktopScriptProvider()) {
this.desktopScriptProvider = this.deps.createDesktopScriptProvider()
return this.desktopScriptProvider
}
return null
}
shutdown(): void {
this.nativeMacOSProvider?.shutdown()
this.nativeMacOSProvider = null
this.desktopScriptProvider?.shutdown()
this.desktopScriptProvider = null
}
}
const lifecycle = new ComputerProviderLifecycle()
export function currentComputerProvider(): ComputerProvider | null {
return lifecycle.current()
}
export function shutdownComputerProviders(): void {
lifecycle.shutdown()
}
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest'
import { computerProviderUnavailableMessage } from './computer-provider-unavailable-message'
describe('computerProviderUnavailableMessage', () => {
it('gives macOS developers the helper build and restart step', () => {
expect(computerProviderUnavailableMessage('darwin')).toContain(
'run pnpm build:computer-macos and restart Orca from this worktree'
)
expect(computerProviderUnavailableMessage('darwin')).toContain(
'Orca Computer Use.app was not found or this macOS version is unsupported'
)
})
it('keeps unsupported platforms explicit', () => {
expect(computerProviderUnavailableMessage('freebsd')).toBe(
'computer-use has no native provider for freebsd'
)
})
})
@@ -0,0 +1,12 @@
export function computerProviderUnavailableMessage(platform: NodeJS.Platform): string {
if (platform === 'darwin') {
return [
'computer-use has no native provider for darwin because Orca Computer Use.app was not found or this macOS version is unsupported.',
'For local development, run pnpm build:computer-macos and restart Orca from this worktree.'
].join(' ')
}
if (platform === 'linux' || platform === 'win32') {
return `computer-use has no native provider for ${platform}; the platform runtime file was not found`
}
return `computer-use has no native provider for ${platform}`
}
+230
View File
@@ -0,0 +1,230 @@
import type {
ComputerActionMetadata,
ComputerProviderCapabilities
} from '../../shared/runtime-types'
import { optionalNumberParam, optionalStringParam } from './desktop-script-provider-params'
import { RuntimeClientError } from './runtime-client-error'
import type {
BridgeElement,
BridgeRequest,
BridgeSnapshot,
NativeActionMethod
} from './desktop-script-provider-types'
export function bridgeTool(method: NativeActionMethod): string {
return {
click: 'click',
performSecondaryAction: 'perform_secondary_action',
scroll: 'scroll',
drag: 'drag',
typeText: 'type_text',
pressKey: 'press_key',
hotkey: 'hotkey',
pasteText: 'paste_text',
setValue: 'set_value'
}[method]
}
export function actionCapabilityKey(
method: NativeActionMethod
): keyof ComputerProviderCapabilities['supports']['actions'] {
const keys = {
click: 'click',
performSecondaryAction: 'performAction',
scroll: 'scroll',
drag: 'drag',
typeText: 'typeText',
pressKey: 'pressKey',
hotkey: 'hotkey',
pasteText: 'pasteText',
setValue: 'setValue'
} satisfies Record<NativeActionMethod, keyof ComputerProviderCapabilities['supports']['actions']>
return keys[method]
}
function desktopActionMetadata(
method: NativeActionMethod,
targetWindowId: number | null,
targetWindowIndex: number | null
): ComputerActionMetadata {
const path =
method === 'pasteText'
? ('clipboard' as const)
: method === 'setValue' || method === 'performSecondaryAction'
? ('accessibility' as const)
: ('synthetic' as const)
return {
path,
actionName:
method === 'hotkey'
? 'hotkey'
: method === 'pasteText'
? 'paste'
: method === 'setValue'
? 'setValue'
: method === 'performSecondaryAction'
? 'performSecondaryAction'
: method === 'typeText'
? 'typeText'
: method === 'pressKey'
? 'pressKey'
: null,
fallbackReason: null,
targetWindowId,
targetWindowIndex,
verification:
method === 'hotkey' || method === 'pasteText'
? {
state: 'unverified' as const,
reason:
method === 'pasteText' ? ('clipboard_paste' as const) : ('synthetic_input' as const)
}
: undefined
}
}
export function desktopActionWindowTarget(
explicitWindowId: number | undefined,
explicitWindowIndex: number | undefined,
current: BridgeSnapshot | null
): Pick<BridgeRequest, 'windowId' | 'windowIndex'> {
if (explicitWindowId !== undefined) {
return { windowId: explicitWindowId }
}
if (explicitWindowIndex !== undefined) {
return { windowIndex: explicitWindowIndex }
}
if (current?.windowId !== null && current?.windowId !== undefined) {
return { windowId: current.windowId }
}
if (current?.windowIndex !== null && current?.windowIndex !== undefined) {
return { windowIndex: current.windowIndex }
}
return {}
}
export function desktopActionMetadataFromResponse(
action: ComputerActionMetadata | undefined,
method: NativeActionMethod,
targetWindowId: number | null,
targetWindowIndex: number | null
): ComputerActionMetadata {
return action
? {
...action,
targetWindowId: action.targetWindowId ?? targetWindowId,
targetWindowIndex: action.targetWindowIndex ?? targetWindowIndex
}
: desktopActionMetadata(method, targetWindowId, targetWindowIndex)
}
export function verifyDesktopAction(
action: ComputerActionMetadata,
method: NativeActionMethod,
params: Record<string, unknown>,
rawAction: ComputerActionMetadata | undefined,
snapshot: BridgeSnapshot | undefined,
targetElement: BridgeElement | undefined
): ComputerActionMetadata {
if (rawAction?.verification) {
return action
}
if (method === 'typeText' || method === 'pressKey' || method === 'hotkey') {
return {
...action,
verification: { state: 'unverified', reason: 'synthetic_input' }
}
}
if (method === 'pasteText') {
return {
...action,
verification: { state: 'unverified', reason: 'clipboard_paste' }
}
}
if (method !== 'setValue') {
return action
}
const expected = optionalStringParam(params, 'value')
const elementIndex = optionalNumberParam(params, 'elementIndex')
if (expected === undefined || elementIndex === undefined) {
return action
}
const actual = refreshedElementValue(snapshot, targetElement, elementIndex)
if (actual === expected) {
return {
...action,
verification: { state: 'verified', property: 'value', expected, actualPreview: actual }
}
}
return {
...action,
verification: {
state: 'unverified',
reason: actual === undefined ? 'provider_unavailable' : 'value_mismatch',
expected,
actualPreview: actual ?? null
}
}
}
function refreshedElementValue(
snapshot: BridgeSnapshot | undefined,
targetElement: BridgeElement | undefined,
fallbackIndex: number
): string | undefined {
const elements = snapshot?.elements ?? []
// Why: app re-renders can reassign sparse element indexes after the action;
// verification should follow the provider identity of the acted-on element.
const identityMatch = targetElement
? elements.find((element) => sameElementIdentity(element, targetElement))
: undefined
return (identityMatch ?? elements.find((element) => element.index === fallbackIndex))?.value
}
function sameElementIdentity(left: BridgeElement, right: BridgeElement): boolean {
if (left.runtimeId !== undefined && right.runtimeId !== undefined) {
return stableIdentityKey(left.runtimeId) === stableIdentityKey(right.runtimeId)
}
if (left.automationId && right.automationId) {
return left.automationId === right.automationId
}
return false
}
function stableIdentityKey(value: unknown): string {
return JSON.stringify(value) ?? String(value)
}
export function cacheParamsForActionResult(
params: Record<string, unknown>,
action: ComputerActionMetadata
): Record<string, unknown> {
if (!isWindowChangedAction(action)) {
return params
}
const { windowId: _windowId, windowIndex: _windowIndex, ...withoutStaleWindowTarget } = params
return withoutStaleWindowTarget
}
export function isWindowChangedAction(action: ComputerActionMetadata): boolean {
return (
action.verification?.state === 'unverified' && action.verification.reason === 'window_changed'
)
}
export function elementParam(
snapshot: BridgeSnapshot | null,
index: number | undefined
): BridgeElement | undefined {
if (index === undefined) {
return undefined
}
const element = snapshot?.elements?.find((candidate) => candidate.index === index)
if (!element) {
throw new RuntimeClientError(
'element_not_found',
`element ${index} is not in the current cached snapshot; run get-app-state again and use a fresh element index`
)
}
return element
}
@@ -0,0 +1,271 @@
import { afterEach, describe, expect, it } from 'vitest'
import {
createDesktopScriptProviderClient,
expectDesktopProviderSubprocessStartCount,
mockBridgeResponse,
resetDesktopScriptProviderTestHarness,
sampleBridgeSnapshot,
sampleCapabilities
} from './desktop-script-provider-test-harness'
describe('DesktopScriptProviderClient action errors', () => {
afterEach(resetDesktopScriptProviderTestHarness)
it('maps action-specific bridge errors to actionable codes', async () => {
mockBridgeResponse({ ok: false, error: 'element value is not settable' })
mockBridgeResponse({ ok: false, error: 'Raise is not a valid secondary action' })
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'value_not_settable'
})
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'action_not_supported'
})
})
it('maps native validation bridge errors to invalid arguments', async () => {
mockBridgeResponse({ ok: false, error: 'unsupported scroll direction: diagonal' })
mockBridgeResponse({ ok: false, error: 'x is required' })
mockBridgeResponse({ ok: false, error: 'text is required' })
mockBridgeResponse({ ok: false, error: 'click_count must be a positive integer' })
mockBridgeResponse({ ok: false, error: 'Unsupported key: Nope' })
const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1')
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'invalid_argument'
})
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'invalid_argument'
})
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'invalid_argument'
})
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'invalid_argument'
})
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'invalid_argument'
})
})
it('does not confuse permission setup errors with invalid arguments', async () => {
mockBridgeResponse({ ok: false, error: 'Accessibility permission is required' })
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'permission_denied'
})
})
it('does not confuse accessibility permission failures with missing windows', async () => {
mockBridgeResponse({
ok: false,
error:
"app 'Text Editor' has visible windows but no accessibility window. Accessibility permission may need to be toggled."
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'permission_denied'
})
})
it('maps keyboard focus bridge errors to window_not_focused', async () => {
mockBridgeResponse({
ok: false,
error:
'window_not_focused: keyboard input requires the target window to be focused; retry with --restore-window'
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'window_not_focused'
})
})
it('maps bridge screenshot capture errors to screenshot_failed', async () => {
mockBridgeResponse({
ok: false,
error: 'screenshot_failed: Screen Recording permission is required'
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'screenshot_failed'
})
})
it('maps missing Linux keyboard dependencies to unsupported capability', async () => {
mockBridgeResponse({
ok: false,
error: 'GDK is required for non-character key synthesis'
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'unsupported_capability'
})
})
it('rejects actions that the provider does not advertise', async () => {
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities({
hotkey: false,
pasteText: false
})
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(
client.action('pasteText', { app: 'Text Editor', text: 'hello' })
).rejects.toMatchObject({
code: 'unsupported_capability',
message: expect.stringContaining('actions.pasteText')
})
})
it('rejects malformed action payloads before launching the native bridge', async () => {
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.action('click', { elementIndex: 0 })).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Missing app')
})
await expect(client.action('click', { app: 'Text Editor' })).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Click requires')
})
await expect(
client.action('click', { app: 'Text Editor', windowId: 1, windowIndex: 0, x: 1, y: 2 })
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('either windowId or windowIndex')
})
await expect(
client.action('scroll', { app: 'Text Editor', elementIndex: 0, direction: 'diagonal' })
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Unsupported direction')
})
await expect(
client.action('drag', { app: 'Text Editor', fromX: 1, fromY: 2 })
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Drag coordinates')
})
await expect(
client.action('performSecondaryAction', { app: 'Text Editor', elementIndex: 0 })
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Missing action')
})
await expect(client.action('typeText', { app: 'Text Editor', text: '' })).rejects.toMatchObject(
{
code: 'invalid_argument',
message: expect.stringContaining('Missing text')
}
)
await expect(
client.action('pressKey', { app: 'Text Editor', key: 'CmdOrCtrl+V' })
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Press-key accepts one key only')
})
await expect(client.action('hotkey', { app: 'Text Editor', key: 'A' })).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Hotkey requires')
})
await expect(
client.action('setValue', { app: 'Text Editor', elementIndex: 0 })
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Missing value')
})
expectDesktopProviderSubprocessStartCount(0)
})
it('rejects non-keyboard actions that the provider does not advertise', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities({
setValue: false
})
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
await expect(
client.action('setValue', {
app: 'Text Editor',
elementIndex: 0,
value: 'changed',
noScreenshot: true
})
).rejects.toMatchObject({
code: 'unsupported_capability',
message: expect.stringContaining('actions.setValue')
})
})
it('uses provider action metadata when bridge reports the actual path', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
action: {
path: 'accessibility',
actionName: 'Press',
fallbackReason: null
},
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
await expect(
client.action('click', {
app: 'Text Editor',
elementIndex: 0,
noScreenshot: true
})
).resolves.toMatchObject({
action: {
path: 'accessibility',
actionName: 'Press'
}
})
})
it('explains that missing element indexes require a fresh snapshot', async () => {
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(
client.action('click', { app: 'Text Editor', elementIndex: 4 })
).rejects.toMatchObject({
code: 'element_not_found',
message: expect.stringContaining('run get-app-state again')
})
})
})
@@ -0,0 +1,285 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
createDesktopScriptProviderClient,
expectDesktopProviderSubprocessStartCount,
mockBridgeResponse,
resetDesktopScriptProviderTestHarness,
sampleBridgeSnapshot,
sampleCapabilities
} from './desktop-script-provider-test-harness'
describe('DesktopScriptProviderClient actions', () => {
afterEach(resetDesktopScriptProviderTestHarness)
it('forwards restore-window to desktop providers', async () => {
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'get_app_state',
restoreWindow: true
})
}
)
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'set_value',
restoreWindow: true
})
}
)
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', restoreWindow: true })
const result = await client.action('setValue', {
app: 'Text Editor',
elementIndex: 0,
value: 'changed',
restoreWindow: true,
noScreenshot: true
})
expect(result.action).toMatchObject({
path: 'accessibility',
actionName: 'setValue',
verification: {
state: 'verified',
property: 'value',
expected: 'changed',
actualPreview: 'changed'
}
})
})
it('marks set-value unverified when the refreshed snapshot does not contain the requested value', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'unchanged')
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
const result = await client.action('setValue', {
app: 'Text Editor',
elementIndex: 0,
value: 'changed',
noScreenshot: true
})
expect(result.action).toMatchObject({
path: 'accessibility',
actionName: 'setValue',
verification: {
state: 'unverified',
reason: 'value_mismatch',
expected: 'changed',
actualPreview: 'unchanged'
}
})
})
it('verifies set-value against the same element when refreshed indexes shift', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'ignored'),
treeLines: ['0 text entry area, Value: other', '7 text entry area, Value: changed'],
elements: [
{
index: 0,
runtimeId: [9, 9],
value: 'other'
},
{
index: 7,
runtimeId: [0, 0],
value: 'changed'
}
]
}
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
const result = await client.action('setValue', {
app: 'Text Editor',
elementIndex: 0,
value: 'changed',
noScreenshot: true
})
expect(result.action).toMatchObject({
verification: {
state: 'verified',
property: 'value',
expected: 'changed',
actualPreview: 'changed'
}
})
})
it('marks synthetic keyboard actions unverified when the provider cannot verify delivery', async () => {
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const result = await client.action('typeText', {
app: 'Text Editor',
text: 'draft body',
noScreenshot: true
})
expect(result.action).toMatchObject({
path: 'synthetic',
actionName: 'typeText',
verification: {
state: 'unverified',
reason: 'synthetic_input'
}
})
})
it('marks synthetic pointer actions unverified when the provider cannot verify delivery', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
const result = await client.action('click', {
app: 'Text Editor',
elementIndex: 0,
noScreenshot: true
})
expect(result.action).toMatchObject({
path: 'synthetic',
verification: {
state: 'unverified',
reason: 'synthetic_input'
}
})
})
it('marks provider-reported clipboard paste unverified when verification is missing', async () => {
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
action: {
path: 'clipboard',
actionName: 'paste',
fallbackReason: null
},
snapshot: sampleBridgeSnapshot('Text Editor', 'pasted')
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const result = await client.action('pasteText', {
app: 'Text Editor',
text: 'draft body',
noScreenshot: true
})
expect(result.action).toMatchObject({
path: 'clipboard',
actionName: 'paste',
verification: {
state: 'unverified',
reason: 'clipboard_paste'
}
})
})
it('keeps window-index snapshots scoped to the matching session', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', session: 'agent-a', windowIndex: 0 })
await expect(
client.action('click', {
app: 'Text Editor',
session: 'agent-b',
windowIndex: 0,
elementIndex: 0
})
).rejects.toMatchObject({ code: 'element_not_found' })
})
it('expires cached desktop snapshots before using old element indexes', async () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-06-04T12:00:00.000Z'))
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
await vi.advanceTimersByTimeAsync(120_001)
await expect(
client.action('click', { app: 'Text Editor', elementIndex: 0, noScreenshot: true })
).rejects.toMatchObject({
code: 'element_not_found',
message: expect.stringContaining('fresh element index')
})
expectDesktopProviderSubprocessStartCount(1)
})
})
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import { mapBridgeError } from './desktop-script-provider-bridge'
describe('mapBridgeError', () => {
it('maps native window-not-found messages without broad false positives', () => {
expect(mapBridgeError('No top-level AT-SPI window is available for Text Editor').code).toBe(
'window_not_found'
)
expect(mapBridgeError("app 'Finder' has no on-screen window").code).toBe('window_not_found')
expect(mapBridgeError('Failed to execute window operation').code).toBe('accessibility_error')
})
it('maps native element-not-found messages without broad false positives', () => {
expect(
mapBridgeError('stale element frame; run get-app-state again and use a fresh element index')
.code
).toBe('element_not_found')
expect(mapBridgeError('unknown element_index').code).toBe('element_not_found')
expect(mapBridgeError('element metadata unavailable').code).toBe('accessibility_error')
})
})
@@ -0,0 +1,172 @@
import { execFile } from 'child_process'
import { RuntimeClientError } from './runtime-client-error'
import type { DesktopScriptPlatform } from './desktop-script-provider-paths'
const REQUEST_TIMEOUT_MS = 30_000
const FORCE_KILL_GRACE_MS = 1_000
export function execBridge(
platform: DesktopScriptPlatform,
scriptPath: string,
operationPath: string
): Promise<{ stdout: string; stderr: string }> {
const command = platform === 'windows' ? 'powershell.exe' : 'python3'
const args =
platform === 'windows'
? [
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Bypass',
'-File',
scriptPath,
operationPath
]
: [scriptPath, operationPath]
return new Promise((resolve, reject) => {
let child: ReturnType<typeof execFile> | null = null
let settled = false
let forceKillTimer: ReturnType<typeof setTimeout> | null = null
const clearForceKillTimer = (): void => {
if (forceKillTimer) {
clearTimeout(forceKillTimer)
forceKillTimer = null
}
}
const finish = (
error: Error | null,
result?: { stdout: string; stderr: string },
options: { keepForceKillTimer?: boolean } = {}
): void => {
if (settled) {
return
}
settled = true
clearTimeout(timeout)
if (!options.keepForceKillTimer) {
clearForceKillTimer()
}
if (error) {
reject(error)
return
}
resolve(result ?? { stdout: '', stderr: '' })
}
// Why: native automation can hang inside platform APIs; reject promptly,
// then escalate cleanup if the bridge ignores the graceful termination.
const timeout = setTimeout(() => {
child?.kill('SIGTERM')
forceKillTimer = setTimeout(() => {
child?.kill('SIGKILL')
forceKillTimer = null
}, FORCE_KILL_GRACE_MS)
finish(
new RuntimeClientError(
'action_timeout',
`desktop provider timed out after ${REQUEST_TIMEOUT_MS}ms`
),
undefined,
{ keepForceKillTimer: true }
)
}, REQUEST_TIMEOUT_MS)
try {
child = execFile(
command,
args,
{
env: process.env,
maxBuffer: 20 * 1024 * 1024,
timeout: REQUEST_TIMEOUT_MS,
windowsHide: true
},
(error, stdout, stderr) => {
if (error) {
const message = stderr.trim() || stdout.trim() || error.message
finish(
error.killed
? new RuntimeClientError('action_timeout', message)
: mapBridgeError(message)
)
return
}
finish(null, { stdout, stderr })
}
)
child?.once('exit', clearForceKillTimer)
} catch (error) {
finish(mapBridgeError(error instanceof Error ? error.message : String(error)))
}
})
}
export function mapBridgeError(message: string): RuntimeClientError {
const text = message.trim() || 'desktop provider failed'
if (/appNotFound|app not found/i.test(text)) {
return new RuntimeClientError('app_not_found', text)
}
if (/appBlocked|app blocked/i.test(text)) {
return new RuntimeClientError('app_blocked', text)
}
if (
/unsupported capability|hotkey.*require|paste_text requires|GDK is required for non-character key synthesis/i.test(
text
)
) {
return new RuntimeClientError('unsupported_capability', text)
}
if (
/unsupported mouse button|unsupported scroll direction|unsupported (?:key|modifier)|windowId is not supported|must be a positive|must be a finite number|\b(?:x|y|from_x|from_y|to_x|to_y|pages|click_count|text|key|direction) is required\b/i.test(
text
)
) {
return new RuntimeClientError('invalid_argument', text)
}
if (/ModuleNotFoundError: No module named 'gi'|PyGObject|python3-gi/i.test(text)) {
return new RuntimeClientError(
'unsupported_capability',
'Linux Computer Use requires python3-gi and AT-SPI packages. Install python3-gi gir1.2-atspi-2.0 at-spi2-core, then retry.'
)
}
if (/not a valid secondary action|action.*not supported/i.test(text)) {
return new RuntimeClientError('action_not_supported', text)
}
if (/value is not settable|not settable/i.test(text)) {
return new RuntimeClientError('value_not_settable', text)
}
if (/stale element|fresh element index/i.test(text)) {
return new RuntimeClientError('element_not_found', text)
}
if (/windowStale|window stale/i.test(text)) {
return new RuntimeClientError('window_stale', text)
}
if (
/window_not_focused|keyboard input requires.*window.*focused|target window.*focused/i.test(text)
) {
return new RuntimeClientError('window_not_focused', text)
}
if (/screenshot_failed|screenshot.*failed|screen recording|payload cap/i.test(text)) {
return new RuntimeClientError('screenshot_failed', text)
}
if (
/window_not_found|No top-level(?: AT-SPI| UI Automation)? window|has no (?:on-screen |accessibility )?window|could not match accessibility window|unknown window(?:_index| id)?/i.test(
text
)
) {
return new RuntimeClientError('window_not_found', text)
}
if (/permission|desktop session|DBUS|XDG_RUNTIME_DIR|AT-SPI/i.test(text)) {
return new RuntimeClientError('permission_denied', text)
}
if (
/element_not_found|stale element|fresh element index|unknown element_index|element \d+ is stale|element indexes require|element \d+ changed since|element \d+ is not in the current cached snapshot/i.test(
text
)
) {
return new RuntimeClientError('element_not_found', text)
}
return new RuntimeClientError('accessibility_error', text)
}
@@ -0,0 +1,108 @@
import { afterEach, describe, expect, it } from 'vitest'
import {
createDesktopScriptProviderClient,
mockBridgeResponse,
resetDesktopScriptProviderTestHarness,
sampleBridgeSnapshot,
sampleCapabilities
} from './desktop-script-provider-test-harness'
describe('DesktopScriptProviderClient cache lifecycle', () => {
afterEach(resetDesktopScriptProviderTestHarness)
it('invalidates stale window selector aliases after a window-changed action fallback', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
action: {
path: 'synthetic',
actionName: 'click',
fallbackReason: null,
verification: { state: 'unverified', reason: 'window_changed' }
},
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'fallback'),
windowId: 123,
windowTitle: 'Fallback Window'
}
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', session: 'agent-a', windowIndex: 0 })
await client.action('click', {
app: 'Text Editor',
session: 'agent-a',
windowIndex: 0,
elementIndex: 0,
noScreenshot: true
})
await expect(
client.action('click', {
app: 'Text Editor',
session: 'agent-a',
windowIndex: 0,
elementIndex: 0,
noScreenshot: true
})
).rejects.toMatchObject({ code: 'element_not_found' })
const cached = (client as unknown as { snapshots: Map<string, { windowId?: number | null }> })
.snapshots
expect(cached.get('session:agent-a:text editor#window-index:0')).toBeUndefined()
expect(cached.get('session:agent-a:text editor')?.windowId).toBe(123)
})
it('bounds cached desktop snapshots while keeping recent aliases usable', async () => {
const snapshotCount = 40
for (let index = 0; index < snapshotCount; index++) {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot(`App ${index}`, `value ${index}`),
snapshotId: `snap-${index}`,
app: { name: `App ${index}`, bundleIdentifier: `bundle.${index}`, pid: 100 + index },
windowId: 1_000 + index,
windowTitle: `Window ${index}`
}
})
}
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('App 39', 'clicked')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'click',
app: 'App 39',
element: expect.objectContaining({ index: 0 })
})
}
)
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
for (let index = 0; index < snapshotCount; index++) {
await client.snapshot({ app: `App ${index}` })
}
await expect(client.action('click', { app: 'App 0', elementIndex: 0 })).rejects.toMatchObject({
code: 'element_not_found'
})
await expect(
client.action('click', { app: 'App 39', elementIndex: 0, noScreenshot: true })
).resolves.toMatchObject({ snapshot: { app: { name: 'App 39' } } })
})
})
@@ -0,0 +1,319 @@
import { afterEach, describe, expect, it } from 'vitest'
import {
createDesktopScriptProviderClient,
mockBridgeResponse,
resetDesktopScriptProviderTestHarness,
sampleBridgeSnapshot,
sampleCapabilities
} from './desktop-script-provider-test-harness'
describe('DesktopScriptProviderClient snapshot cache', () => {
afterEach(resetDesktopScriptProviderTestHarness)
it('targets cached ID-less snapshots by their provider window index on follow-up actions', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
windowId: null,
windowIndex: 3
}
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse(
{
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'changed'),
windowId: null,
windowIndex: 3
}
},
(operation) => {
expect(operation).toMatchObject({
tool: 'set_value',
app: 'Text Editor',
windowIndex: 3,
element: expect.objectContaining({ index: 0 })
})
expect(operation.windowId).toBeUndefined()
}
)
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
await client.action('setValue', {
app: 'Text Editor',
elementIndex: 0,
value: 'changed',
noScreenshot: true
})
})
it('aliases provider window indexes for explicit follow-up actions after an ID-less snapshot', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
windowId: null,
windowIndex: 3
}
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse(
{
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'changed'),
windowId: null,
windowIndex: 3
}
},
(operation) => {
expect(operation).toMatchObject({
tool: 'set_value',
windowIndex: 3,
element: expect.objectContaining({ index: 0 })
})
expect(operation.windowId).toBeUndefined()
}
)
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
await client.action('setValue', {
app: 'Text Editor',
windowIndex: 3,
elementIndex: 0,
value: 'changed',
noScreenshot: true
})
})
it('aliases cached snapshots by documented pid selector for follow-up actions', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'set_value',
app: 'pid:100',
windowId: 99,
element: expect.objectContaining({ index: 0 })
})
}
)
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
await client.action('setValue', {
app: 'pid:100',
elementIndex: 0,
value: 'changed',
noScreenshot: true
})
})
it('aliases cached window-index snapshots by documented pid selector', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
windowId: null,
windowIndex: 3
}
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse(
{
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'changed'),
windowId: null,
windowIndex: 3
}
},
(operation) => {
expect(operation).toMatchObject({
tool: 'set_value',
app: 'pid:100',
windowIndex: 3,
element: expect.objectContaining({ index: 0 })
})
expect(operation.windowId).toBeUndefined()
}
)
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', windowIndex: 3 })
await client.action('setValue', {
app: 'pid:100',
windowIndex: 3,
elementIndex: 0,
value: 'changed',
noScreenshot: true
})
})
it('does not alias cached snapshots by invalid provider pids', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 0 }
}
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
const cacheKeys = [
...(client as unknown as { snapshots: Map<string, unknown> }).snapshots.keys()
]
expect(cacheKeys).not.toContain('pid:0')
expect(cacheKeys).not.toContain('default:pid:0')
expect(cacheKeys).not.toContain('0')
expect(cacheKeys).not.toContain('default:0')
})
it('drops focused element ids that are not present in the rendered element records', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
focusedElementId: 99
}
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const result = await client.snapshot({ app: 'Text Editor' })
expect(result.snapshot.focusedElementId).toBeNull()
})
it('does not retain screenshot bytes in the follow-up action cache', async () => {
const largeScreenshot = 'x'.repeat(1024 * 1024)
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
screenshotPngBase64: largeScreenshot
}
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const result = await client.snapshot({ app: 'Text Editor' })
const cached = [
...(
client as unknown as { snapshots: Map<string, { screenshotPngBase64?: string | null }> }
).snapshots.values()
]
expect(result.screenshot?.data).toBe(largeScreenshot)
expect(cached.length).toBeGreaterThan(0)
expect(cached.every((snapshot) => snapshot.screenshotPngBase64 === null)).toBe(true)
})
it('targets cached elements by session and window id after observe without a window selector', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'click',
app: 'Text Editor',
windowId: 99,
element: expect.objectContaining({ index: 0 })
})
}
)
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', session: 'agent-a' })
await client.action('click', {
app: 'Text Editor',
session: 'agent-a',
windowId: 99,
elementIndex: 0,
noScreenshot: true
})
})
it('targets cached elements by session and explicit window index without forwarding window id', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'drag',
app: 'Text Editor',
windowIndex: 0,
fromElement: expect.objectContaining({ index: 0 }),
toElement: expect.objectContaining({ index: 0 })
})
expect(operation.windowId).toBeUndefined()
expect(operation.from_x).toBeUndefined()
expect(operation.to_x).toBeUndefined()
expect(operation.windowBounds).toBeNull()
}
)
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', session: 'agent-a', windowIndex: 0 })
await client.action('drag', {
app: 'Text Editor',
session: 'agent-a',
windowIndex: 0,
fromElementIndex: 0,
toElementIndex: 0
})
})
})
@@ -1,39 +1,15 @@
/* eslint-disable max-lines -- Why: desktop provider contract coverage shares one mocked bridge harness. */
import { execFile } from 'child_process'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { DesktopScriptProviderClient } from './desktop-script-provider-client'
import { afterEach, describe, expect, it } from 'vitest'
import {
createDesktopScriptProviderClient,
mockBridgeResponse,
publicSnapshotKeys,
resetDesktopScriptProviderTestHarness,
sampleBridgeSnapshot,
sampleCapabilities
} from './desktop-script-provider-test-harness'
const { operationFiles, mkdtempMock, rmMock, writeFileMock } = vi.hoisted(() => {
const files = new Map<string, string>()
return {
operationFiles: files,
mkdtempMock: vi.fn(async (prefix: string) => `${prefix}${files.size}`),
rmMock: vi.fn(async () => undefined),
writeFileMock: vi.fn(async (filePath: string, data: string | Buffer) => {
files.set(filePath, Buffer.isBuffer(data) ? data.toString('utf8') : data)
})
}
})
vi.mock('child_process', () => ({
execFile: vi.fn()
}))
vi.mock('fs/promises', () => ({
mkdtemp: mkdtempMock,
rm: rmMock,
writeFile: writeFileMock
}))
describe('DesktopScriptProviderClient', () => {
afterEach(() => {
vi.useRealTimers()
vi.mocked(execFile).mockReset()
operationFiles.clear()
mkdtempMock.mockClear()
rmMock.mockClear()
writeFileMock.mockClear()
})
describe('DesktopScriptProviderClient snapshots', () => {
afterEach(resetDesktopScriptProviderTestHarness)
it('normalizes list-apps responses', async () => {
mockBridgeResponse({
@@ -41,7 +17,7 @@ describe('DesktopScriptProviderClient', () => {
apps: [{ name: 'Notepad', bundleIdentifier: 'notepad', pid: 42 }]
})
const client = new DesktopScriptProviderClient('windows', '/tmp/runtime.ps1')
const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1')
await expect(client.listApps()).resolves.toEqual({
apps: [
@@ -62,12 +38,16 @@ describe('DesktopScriptProviderClient', () => {
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
})
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const initial = await client.snapshot({ app: 'Text Editor' })
expect(initial.snapshot.elementCount).toBe(1)
@@ -101,10 +81,6 @@ describe('DesktopScriptProviderClient', () => {
value: 'changed',
noScreenshot: true
})
const secondCall = vi.mocked(execFile).mock.calls[1]
const operationPath = secondCall[1]?.at(-1)
expect(typeof operationPath).toBe('string')
})
it('uses bridge screenshot dimensions when the native payload is downscaled', async () => {
@@ -118,7 +94,7 @@ describe('DesktopScriptProviderClient', () => {
}
})
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const result = await client.snapshot({ app: 'Text Editor' })
@@ -135,440 +111,92 @@ describe('DesktopScriptProviderClient', () => {
})
})
it('targets cached elements by session and explicit window id', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'drag',
app: 'Text Editor',
windowId: 99,
windowIndex: 0,
fromElement: expect.objectContaining({ index: 0 }),
toElement: expect.objectContaining({ index: 0 })
})
expect(operation.from_x).toBeUndefined()
expect(operation.to_x).toBeUndefined()
expect(operation.windowBounds).toBeNull()
}
)
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', session: 'agent-a', windowId: 99 })
await client.action('drag', {
app: 'Text Editor',
session: 'agent-a',
windowId: 99,
windowIndex: 0,
fromElementIndex: 0,
toElementIndex: 0
})
})
it('forwards restore-window to desktop providers', async () => {
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'get_app_state',
restoreWindow: true
})
}
)
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'set_value',
restoreWindow: true
})
}
)
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', restoreWindow: true })
const result = await client.action('setValue', {
app: 'Text Editor',
elementIndex: 0,
value: 'changed',
restoreWindow: true,
noScreenshot: true
})
expect(result.action).toMatchObject({
path: 'accessibility',
actionName: 'setValue'
})
})
it('keeps window-index snapshots scoped to the matching session', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', session: 'agent-a', windowIndex: 0 })
await expect(
client.action('click', {
app: 'Text Editor',
session: 'agent-b',
windowIndex: 0,
elementIndex: 0
})
).rejects.toMatchObject({ code: 'element_not_found' })
})
it('bounds cached desktop snapshots while keeping recent aliases usable', async () => {
const snapshotCount = 40
for (let index = 0; index < snapshotCount; index++) {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot(`App ${index}`, `value ${index}`),
snapshotId: `snap-${index}`,
app: { name: `App ${index}`, bundleIdentifier: `bundle.${index}`, pid: 100 + index },
windowId: 1_000 + index,
windowTitle: `Window ${index}`
}
})
}
mockBridgeResponse(
{
ok: true,
snapshot: sampleBridgeSnapshot('App 39', 'clicked')
},
(operation) => {
expect(operation).toMatchObject({
tool: 'click',
app: 'App 39',
element: expect.objectContaining({ index: 0 })
})
}
)
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
for (let index = 0; index < snapshotCount; index++) {
await client.snapshot({ app: `App ${index}` })
}
await expect(client.action('click', { app: 'App 0', elementIndex: 0 })).rejects.toMatchObject({
code: 'element_not_found'
})
await expect(
client.action('click', { app: 'App 39', elementIndex: 0, noScreenshot: true })
).resolves.toMatchObject({ snapshot: { app: { name: 'App 39' } } })
})
it('explains screenshot capture failures while keeping accessibility state usable', async () => {
it('preserves provider window indexes when the snapshot has no stable window id', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
screenshotPngBase64: null
windowId: null,
windowIndex: 3
}
})
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).resolves.toMatchObject({
const result = await client.snapshot({ app: 'Text Editor', windowIndex: 3 })
expect(result.snapshot.window).toMatchObject({
id: null,
index: 3,
title: 'Text Editor'
})
})
it('uses window indexes in fallback snapshot IDs for ID-less provider windows', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
elementCount: 1
},
screenshotStatus: {
state: 'failed',
code: 'screenshot_failed',
message: expect.stringContaining('--no-screenshot')
}
})
})
it('normalizes list-windows responses after provider handshake', async () => {
mockBridgeResponse({
ok: true,
capabilities: {
platform: 'linux',
provider: 'orca-computer-use-linux',
providerVersion: '1.0.0',
protocolVersion: 1,
supports: {
apps: { list: true, bundleIds: false, pids: true },
windows: {
list: true,
targetById: true,
targetByIndex: true,
focus: false,
moveResize: false
},
observation: {
screenshot: true,
annotatedScreenshot: false,
elementFrames: true,
ocr: false
},
actions: {
click: true,
typeText: true,
pressKey: true,
hotkey: false,
pasteText: false,
scroll: true,
drag: true,
setValue: true,
performAction: true
},
surfaces: { menus: false, dialogs: false, dock: false, menubar: false }
}
...sampleBridgeSnapshot('Text Editor', 'first'),
snapshotId: undefined,
windowId: null,
windowIndex: 1
}
})
mockBridgeResponse({
ok: true,
app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 100 },
windows: [
{
index: 0,
app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 100 },
id: 99,
title: 'Document',
x: 10,
y: 20,
width: 300,
height: 200,
isMinimized: false,
isOffscreen: false,
screenIndex: null,
platform: { backend: 'at-spi' }
}
]
})
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.listWindows({ app: 'Text Editor' })).resolves.toMatchObject({
app: { name: 'Text Editor', bundleId: 'Text Editor', pid: 100 },
windows: [{ index: 0, id: 99, title: 'Document' }]
})
})
it('maps bridge app errors to RuntimeClientError codes', async () => {
mockBridgeResponse({ ok: false, error: 'appNotFound("Missing")' })
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Missing' })).rejects.toMatchObject({
code: 'app_not_found'
})
})
it('maps blocked app bridge errors to a policy error', async () => {
mockBridgeResponse({ ok: false, error: 'appBlocked("1Password")' })
const client = new DesktopScriptProviderClient('windows', '/tmp/runtime.ps1')
await expect(client.snapshot({ app: '1Password' })).rejects.toMatchObject({
code: 'app_blocked'
})
})
it('rejects when the desktop provider subprocess ignores the exec timeout', async () => {
vi.useFakeTimers()
const kill = vi.fn()
vi.mocked(execFile).mockImplementationOnce(() => ({ kill }) as never)
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
const promise = client.listApps()
let settled = false
void promise.catch(() => {
settled = true
})
await vi.waitFor(() => expect(execFile).toHaveBeenCalled(), { timeout: 1_000 })
await vi.advanceTimersByTimeAsync(30_001)
await vi.runOnlyPendingTimersAsync()
expect(settled).toBe(true)
expect(kill).toHaveBeenCalled()
await expect(promise).rejects.toMatchObject({ code: 'action_timeout' })
})
it('maps action-specific bridge errors to actionable codes', async () => {
mockBridgeResponse({ ok: false, error: 'element value is not settable' })
mockBridgeResponse({ ok: false, error: 'Raise is not a valid secondary action' })
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'value_not_settable'
})
await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({
code: 'action_not_supported'
})
})
it('rejects actions that the provider does not advertise', async () => {
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities({
hotkey: false,
pasteText: false
})
})
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(
client.action('pasteText', { app: 'Text Editor', text: 'hello' })
).rejects.toMatchObject({
code: 'unsupported_capability',
message: expect.stringContaining('actions.pasteText')
})
})
it('uses provider action metadata when bridge reports the actual path', async () => {
mockBridgeResponse({
ok: true,
snapshot: sampleBridgeSnapshot('Text Editor', 'initial')
})
mockBridgeResponse({
ok: true,
action: {
path: 'accessibility',
actionName: 'Press',
fallbackReason: null
},
snapshot: sampleBridgeSnapshot('Text Editor', 'changed')
})
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor' })
await expect(
client.action('click', {
app: 'Text Editor',
elementIndex: 0,
noScreenshot: true
})
).resolves.toMatchObject({
action: {
path: 'accessibility',
actionName: 'Press'
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'second'),
snapshotId: undefined,
windowId: null,
windowIndex: 2
}
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const first = await client.snapshot({ app: 'Text Editor', windowIndex: 1 })
const second = await client.snapshot({ app: 'Text Editor', windowIndex: 2 })
expect(first.snapshot.id).toContain('window-index:1')
expect(second.snapshot.id).toContain('window-index:2')
expect(first.snapshot.id).not.toBe(second.snapshot.id)
})
it('explains that missing element indexes require a fresh snapshot', async () => {
const client = new DesktopScriptProviderClient('linux', '/tmp/runtime.py')
it('adds target window index metadata for ID-less action results', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
windowId: null,
windowIndex: 3
}
})
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'changed'),
windowId: null,
windowIndex: 3
}
})
await expect(
client.action('click', { app: 'Text Editor', elementIndex: 4 })
).rejects.toMatchObject({
code: 'element_not_found',
message: expect.stringContaining('run get-app-state again')
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await client.snapshot({ app: 'Text Editor', windowIndex: 3 })
const result = await client.action('click', {
app: 'Text Editor',
windowIndex: 3,
elementIndex: 0,
noScreenshot: true
})
expect(result.action).toMatchObject({
targetWindowId: null,
targetWindowIndex: 3
})
})
})
function mockBridgeResponse(
response: unknown,
inspectOperation?: (operation: Record<string, unknown>) => void
): void {
vi.mocked(execFile).mockImplementationOnce((_command, _args, _options, callback) => {
const operationPath = _args?.at(-1)
if (inspectOperation && typeof operationPath === 'string') {
const operation = operationFiles.get(operationPath)
if (!operation) {
throw new Error(`Missing mocked operation file: ${operationPath}`)
}
inspectOperation(JSON.parse(operation) as Record<string, unknown>)
}
const done = callback as (error: Error | null, stdout: string, stderr: string) => void
done(null, JSON.stringify(response), '')
return null as never
})
}
function sampleBridgeSnapshot(name: string, value: string) {
return {
app: { name, bundleIdentifier: name, pid: 100 },
snapshotId: 'snap-test',
windowTitle: name,
windowId: 99,
windowBounds: { x: 10, y: 20, width: 300, height: 200 },
screenshotPngBase64: 'iVBORw0KGgo=',
coordinateSpace: 'window',
truncation: { truncated: false, maxNodes: 1200, maxDepth: 64, maxDepthReached: false },
treeLines: [`0 text entry area, Value: ${value}`],
focusedSummary: 'text entry area',
elements: [
{
index: 0,
runtimeId: [0, 0],
name: 'Body',
controlType: 'text',
localizedControlType: 'text entry area',
value,
frame: { x: 1, y: 2, width: 100, height: 20 },
actions: ['SetValue']
}
]
}
}
function sampleCapabilities(actions: Partial<Record<string, boolean>> = {}) {
return {
platform: 'linux',
provider: 'orca-computer-use-linux',
providerVersion: '1.0.0',
protocolVersion: 1,
supports: {
apps: { list: true, bundleIds: false, pids: true },
windows: {
list: true,
targetById: true,
targetByIndex: true,
focus: false,
moveResize: false
},
observation: {
screenshot: true,
annotatedScreenshot: false,
elementFrames: true,
ocr: false
},
actions: {
click: true,
typeText: true,
pressKey: true,
hotkey: true,
pasteText: true,
scroll: true,
drag: true,
setValue: true,
performAction: true,
...actions
},
surfaces: { menus: false, dialogs: false, dock: false, menubar: false }
}
}
}
function publicSnapshotKeys(snapshot: unknown): string[] {
return Object.keys(snapshot as Record<string, unknown>).sort()
}
@@ -1,176 +1,52 @@
/* eslint-disable max-lines -- Why: bridge schema, request mapping, and result normalization stay together so platform scripts have one audited contract. */
import { execFile } from 'child_process'
import { mkdtemp, rm, writeFile } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import type {
ComputerActionMetadata,
ComputerActionResult,
ComputerListAppsResult,
ComputerListWindowsResult,
ComputerProviderCapabilities,
ComputerSnapshotResult
} from '../../shared/runtime-types'
import {
actionCapabilityKey,
bridgeTool,
cacheParamsForActionResult,
desktopActionMetadataFromResponse,
desktopActionWindowTarget,
elementParam,
isWindowChangedAction,
verifyDesktopAction
} from './desktop-script-action'
import { validateComputerProviderActionParams } from './computer-provider-action-validation'
import { execBridge, mapBridgeError } from './desktop-script-provider-bridge'
import {
optionalNumberParam,
optionalStringParam,
stringParam
} from './desktop-script-provider-params'
import {
desktopScriptPlatform,
resolveDesktopScriptProviderPath,
type DesktopScriptPlatform
} from './desktop-script-provider-paths'
import type {
BridgeRequest,
BridgeResponse,
NativeActionMethod
} from './desktop-script-provider-types'
import { DesktopScriptSnapshotStore } from './desktop-script-snapshot-store'
import { normalizeBridgeApp, renderSnapshot } from './desktop-script-snapshot-rendering'
import { normalizeComputerActionResult } from './computer-action-verification-normalization'
import { RuntimeClientError } from './runtime-client-error'
type NativeMethod =
| 'handshake'
| 'listApps'
| 'listWindows'
| 'getAppState'
| 'click'
| 'performSecondaryAction'
| 'scroll'
| 'drag'
| 'typeText'
| 'pressKey'
| 'hotkey'
| 'pasteText'
| 'setValue'
type NativeActionMethod = Exclude<
NativeMethod,
'handshake' | 'listApps' | 'listWindows' | 'getAppState'
>
type BridgeFrame = {
x: number
y: number
width: number
height: number
}
type BridgeElement = {
index: number
runtimeId?: unknown
automationId?: string
name?: string
controlType?: string
localizedControlType?: string
className?: string
value?: string
nativeWindowHandle?: number
frame?: BridgeFrame | null
actions?: string[]
}
type BridgeSnapshot = {
snapshotId?: string
app: {
name: string
bundleIdentifier?: string
bundleId?: string
pid: number
}
windowTitle?: string
windowId?: number | null
windowBounds?: BridgeFrame | null
screenshotPngBase64?: string | null
screenshotWidth?: number | null
screenshotHeight?: number | null
screenshotScale?: number | null
coordinateSpace?: 'window'
truncation?: {
truncated?: boolean
maxNodes?: number
maxDepth?: number
maxDepthReached?: boolean
}
treeLines?: string[]
focusedSummary?: string | null
focusedElementId?: number | null
selectedText?: string | null
elements?: BridgeElement[]
}
type BridgeWindow = {
index: number
app: {
name: string
bundleIdentifier?: string | null
bundleId?: string | null
pid: number
}
id?: number | null
title: string
x?: number | null
y?: number | null
width: number
height: number
isMinimized?: boolean | null
isOffscreen?: boolean | null
screenIndex?: number | null
platform?: Record<string, unknown>
}
type BridgeResponse = {
ok: boolean
error?: string
capabilities?: ComputerProviderCapabilities
apps?: {
name: string
bundleIdentifier?: string | null
bundleId?: string | null
pid: number
}[]
app?: {
name: string
bundleIdentifier?: string | null
bundleId?: string | null
pid: number
}
windows?: BridgeWindow[]
snapshot?: BridgeSnapshot
action?: ComputerActionMetadata
}
type BridgeRequest = {
tool: string
app?: string
element?: BridgeElement
fromElement?: BridgeElement
toElement?: BridgeElement
x?: number
y?: number
from_x?: number
from_y?: number
to_x?: number
to_y?: number
click_count?: number
mouse_button?: string
action?: string
direction?: string
pages?: number
text?: string
key?: string
value?: string
windowBounds?: BridgeFrame | null
windowId?: number
windowIndex?: number
noScreenshot?: boolean
restoreWindow?: boolean
}
const REQUEST_TIMEOUT_MS = 30_000
const MAX_CACHED_DESKTOP_SNAPSHOTS = 32
type CachedSnapshotEntry = {
snapshot: BridgeSnapshot
keys: string[]
}
export function shouldUseDesktopScriptProvider(): boolean {
return desktopScriptPlatform() !== null && resolveDesktopScriptProviderPath() !== null
}
export class DesktopScriptProviderClient {
private readonly snapshots = new Map<string, BridgeSnapshot>()
private readonly snapshotEntries: CachedSnapshotEntry[] = []
private readonly snapshotStore = new DesktopScriptSnapshotStore()
readonly snapshots = this.snapshotStore.snapshots
private providerCapabilities: ComputerProviderCapabilities | null = null
constructor(
@@ -178,6 +54,11 @@ export class DesktopScriptProviderClient {
private readonly scriptPath: string = requiredScriptPath()
) {}
shutdown(): void {
this.snapshotStore.clear()
this.providerCapabilities = null
}
async listApps(): Promise<ComputerListAppsResult> {
const response = await this.callBridge({ tool: 'list_apps' })
return {
@@ -244,14 +125,19 @@ export class DesktopScriptProviderClient {
method: NativeActionMethod,
params: Record<string, unknown>
): Promise<ComputerActionResult> {
const app = stringParam(params, 'app')
await this.ensureActionSupported(method)
const app = validateComputerProviderActionParams(method, params)
const explicitWindowId = optionalNumberParam(params, 'windowId')
const explicitWindowIndex = optionalNumberParam(params, 'windowIndex')
const current = this.currentSnapshot(app, explicitWindowId, params)
const current = this.snapshotStore.current(app, explicitWindowId, params)
const actionWindowTarget = desktopActionWindowTarget(
explicitWindowId,
explicitWindowIndex,
current
)
const element = elementParam(current, optionalNumberParam(params, 'elementIndex'))
const fromElement = elementParam(current, optionalNumberParam(params, 'fromElementIndex'))
const toElement = elementParam(current, optionalNumberParam(params, 'toElementIndex'))
await this.ensureActionSupported(method)
const response = await this.callBridge({
tool: bridgeTool(method),
app,
@@ -273,23 +159,38 @@ export class DesktopScriptProviderClient {
key: optionalStringParam(params, 'key'),
value: optionalStringParam(params, 'value'),
windowBounds: null,
windowId: explicitWindowId ?? current?.windowId ?? undefined,
windowIndex: explicitWindowIndex,
...actionWindowTarget,
noScreenshot: params.noScreenshot === true,
restoreWindow: params.restoreWindow === true
})
return {
...this.rememberAndRender(app, response, params.noScreenshot === true, params),
action:
response.action ??
desktopActionMetadata(method, response.snapshot?.windowId ?? current?.windowId ?? null)
const action = verifyDesktopAction(
desktopActionMetadataFromResponse(
response.action,
method,
response.snapshot?.windowId ?? current?.windowId ?? null,
response.snapshot?.windowIndex ?? current?.windowIndex ?? null
),
method,
params,
response.action,
response.snapshot,
element
)
if (isWindowChangedAction(action)) {
this.snapshotStore.forgetWindowTarget(app, params, current)
}
return normalizeComputerActionResult({
...this.rememberAndRender(
app,
response,
params.noScreenshot === true,
cacheParamsForActionResult(params, action)
),
action
})
}
private async ensureActionSupported(method: NativeActionMethod): Promise<void> {
if (method !== 'hotkey' && method !== 'pasteText') {
return
}
const capabilities = await this.readCapabilities()
const actionKey = actionCapabilityKey(method)
if (!capabilities.supports.actions[actionKey]) {
@@ -348,451 +249,9 @@ export class DesktopScriptProviderClient {
if (!response.snapshot) {
throw new RuntimeClientError('accessibility_error', 'desktop provider returned no snapshot')
}
this.rememberSnapshot(app, response.snapshot, params)
this.snapshotStore.remember(app, response.snapshot, params)
return renderSnapshot(response.snapshot, noScreenshot)
}
private rememberSnapshot(
query: string,
snapshot: BridgeSnapshot,
params: Record<string, unknown>
): void {
const keys = snapshotCacheKeys(query, snapshot, params)
if (keys.length === 0) {
return
}
const entry = { snapshot, keys }
this.snapshotEntries.push(entry)
for (const key of keys) {
this.snapshots.set(key, snapshot)
}
this.pruneSnapshotCache()
}
private pruneSnapshotCache(): void {
while (this.snapshotEntries.length > MAX_CACHED_DESKTOP_SNAPSHOTS) {
const expired = this.snapshotEntries.shift()
if (!expired) {
return
}
for (const key of expired.keys) {
// Why: newer snapshots can reuse the same alias; only remove aliases
// that still point at the large snapshot payload being evicted.
if (this.snapshots.get(key) === expired.snapshot) {
this.snapshots.delete(key)
}
}
}
}
private currentSnapshot(
app: string,
windowId: number | undefined,
params: Record<string, unknown>
): BridgeSnapshot | null {
const namespace = snapshotNamespace(params)
if (windowId !== undefined) {
const windowKey = snapshotWindowKey(app, windowId)
return (
this.snapshots.get(namespacedSnapshotKey(namespace, windowKey)) ??
(isExplicitSnapshotNamespace(namespace) ? undefined : this.snapshots.get(windowKey)) ??
null
)
}
const windowIndex = optionalNumberParam(params, 'windowIndex')
if (windowIndex !== undefined) {
const windowIndexKey = snapshotWindowIndexKey(app, windowIndex)
return (
this.snapshots.get(namespacedSnapshotKey(namespace, windowIndexKey)) ??
(isExplicitSnapshotNamespace(namespace) ? undefined : this.snapshots.get(windowIndexKey)) ??
null
)
}
return (
this.snapshots.get(namespacedSnapshotKey(namespace, app)) ??
(isExplicitSnapshotNamespace(namespace)
? undefined
: this.snapshots.get(app.toLowerCase())) ??
null
)
}
}
function execBridge(
platform: DesktopScriptPlatform,
scriptPath: string,
operationPath: string
): Promise<{ stdout: string; stderr: string }> {
const command = platform === 'windows' ? 'powershell.exe' : 'python3'
const args =
platform === 'windows'
? [
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Bypass',
'-File',
scriptPath,
operationPath
]
: [scriptPath, operationPath]
return new Promise((resolve, reject) => {
let child: ReturnType<typeof execFile> | null = null
let settled = false
const finish = (error: Error | null, result?: { stdout: string; stderr: string }): void => {
if (settled) {
return
}
settled = true
clearTimeout(timeout)
if (error) {
reject(error)
return
}
resolve(result ?? { stdout: '', stderr: '' })
}
// Why: Node's execFile timeout only sends a signal; a provider process that
// ignores it can still leave the computer-use action promise pending.
const timeout = setTimeout(() => {
child?.kill()
finish(
new RuntimeClientError(
'action_timeout',
`desktop provider timed out after ${REQUEST_TIMEOUT_MS}ms`
)
)
}, REQUEST_TIMEOUT_MS)
try {
child = execFile(
command,
args,
{
env: process.env,
maxBuffer: 20 * 1024 * 1024,
timeout: REQUEST_TIMEOUT_MS,
windowsHide: true
},
(error, stdout, stderr) => {
if (error) {
const message = stderr.trim() || stdout.trim() || error.message
finish(
error.killed
? new RuntimeClientError('action_timeout', message)
: mapBridgeError(message)
)
return
}
finish(null, { stdout, stderr })
}
)
} catch (error) {
finish(mapBridgeError(error instanceof Error ? error.message : String(error)))
}
})
}
function renderSnapshot(snapshot: BridgeSnapshot, noScreenshot: boolean): ComputerSnapshotResult {
const bounds = snapshot.windowBounds
const treeText = renderTreeText(snapshot)
// Why: Linux/Windows providers may downscale screenshots to cap IPC payloads,
// while window bounds remain the unscaled coordinate space for actions.
const screenshotWidth =
positiveRoundedNumber(snapshot.screenshotWidth) ?? Math.max(1, Math.round(bounds?.width ?? 1))
const screenshotHeight =
positiveRoundedNumber(snapshot.screenshotHeight) ?? Math.max(1, Math.round(bounds?.height ?? 1))
const screenshotScale = positiveNumber(snapshot.screenshotScale) ?? 1
const screenshot = snapshot.screenshotPngBase64
? {
data: snapshot.screenshotPngBase64,
format: 'png' as const,
width: screenshotWidth,
height: screenshotHeight,
scale: screenshotScale
}
: null
return {
snapshot: {
// Why: bridge elements can be large; keep them cached internally for actions
// instead of returning duplicated metadata in every agent-facing snapshot.
id: snapshot.snapshotId ?? fallbackSnapshotId(snapshot),
app: {
name: snapshot.app.name,
bundleId: snapshot.app.bundleId ?? snapshot.app.bundleIdentifier ?? null,
pid: snapshot.app.pid
},
window: {
title: snapshot.windowTitle ?? snapshot.app.name,
id: snapshot.windowId ?? null,
x: bounds ? Math.round(bounds.x) : null,
y: bounds ? Math.round(bounds.y) : null,
width: Math.max(0, Math.round(bounds?.width ?? 0)),
height: Math.max(0, Math.round(bounds?.height ?? 0)),
isMinimized: null,
isOffscreen: null,
screenIndex: null
},
coordinateSpace: snapshot.coordinateSpace ?? 'window',
treeText,
elementCount: snapshot.elements?.length ?? 0,
focusedElementId: snapshot.focusedElementId ?? null,
truncation: {
truncated: snapshot.truncation?.truncated === true,
maxNodes: snapshot.truncation?.maxNodes,
maxDepth: snapshot.truncation?.maxDepth,
maxDepthReached: snapshot.truncation?.maxDepthReached === true
}
},
screenshot,
screenshotStatus: screenshot
? {
state: 'captured',
metadata: { engine: 'unknown', windowId: snapshot.windowId ?? null }
}
: noScreenshot
? { state: 'skipped', reason: 'no_screenshot_flag' }
: {
state: 'failed',
code: 'screenshot_failed',
message:
'desktop provider returned no image; grant screen capture permission or pass --no-screenshot to inspect accessibility state only.'
}
}
}
function positiveNumber(value: number | null | undefined): number | null {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null
}
function positiveRoundedNumber(value: number | null | undefined): number | null {
const numberValue = positiveNumber(value)
return numberValue === null ? null : Math.max(1, Math.round(numberValue))
}
function fallbackSnapshotId(snapshot: BridgeSnapshot): string {
const appRef = snapshot.app.bundleId ?? snapshot.app.bundleIdentifier ?? snapshot.app.name
return `${appRef}:${snapshot.app.pid}:${snapshot.windowId ?? 'window'}`
}
function renderTreeText(snapshot: BridgeSnapshot): string {
const appRef = snapshot.app.bundleId ?? snapshot.app.bundleIdentifier ?? snapshot.app.name
const lines = [
`App=${appRef} (pid ${snapshot.app.pid})`,
`Window: "${sanitize(snapshot.windowTitle ?? snapshot.app.name)}", App: ${sanitize(snapshot.app.name)}.`,
'',
...(snapshot.treeLines ?? [])
]
if (snapshot.selectedText) {
lines.push('', `Selected text: [${sanitize(snapshot.selectedText)}]`)
} else if (snapshot.focusedSummary) {
lines.push('', `The focused UI element is ${sanitize(snapshot.focusedSummary)}.`)
}
return lines.join('\n')
}
function bridgeTool(method: NativeActionMethod): string {
return {
click: 'click',
performSecondaryAction: 'perform_secondary_action',
scroll: 'scroll',
drag: 'drag',
typeText: 'type_text',
pressKey: 'press_key',
hotkey: 'hotkey',
pasteText: 'paste_text',
setValue: 'set_value'
}[method]
}
function actionCapabilityKey(
method: NativeActionMethod
): keyof ComputerProviderCapabilities['supports']['actions'] {
const keys = {
click: 'click',
performSecondaryAction: 'performAction',
scroll: 'scroll',
drag: 'drag',
typeText: 'typeText',
pressKey: 'pressKey',
hotkey: 'hotkey',
pasteText: 'pasteText',
setValue: 'setValue'
} satisfies Record<NativeActionMethod, keyof ComputerProviderCapabilities['supports']['actions']>
return keys[method]
}
function desktopActionMetadata(method: NativeActionMethod, targetWindowId: number | null) {
const path =
method === 'pasteText'
? ('clipboard' as const)
: method === 'setValue' || method === 'performSecondaryAction'
? ('accessibility' as const)
: ('synthetic' as const)
return {
path,
actionName:
method === 'hotkey'
? 'hotkey'
: method === 'pasteText'
? 'paste'
: method === 'setValue'
? 'setValue'
: method === 'performSecondaryAction'
? 'performSecondaryAction'
: null,
fallbackReason: null,
targetWindowId,
verification:
method === 'hotkey' || method === 'pasteText'
? {
state: 'unverified' as const,
reason:
method === 'pasteText' ? ('clipboard_paste' as const) : ('synthetic_input' as const)
}
: undefined
}
}
function normalizeBridgeApp(app: BridgeResponse['app'] | BridgeWindow['app'] | undefined) {
if (!app) {
throw new RuntimeClientError('accessibility_error', 'desktop provider returned no app')
}
return {
name: app.name,
bundleId: app.bundleId ?? app.bundleIdentifier ?? null,
pid: app.pid
}
}
function elementParam(
snapshot: BridgeSnapshot | null,
index: number | undefined
): BridgeElement | undefined {
if (index === undefined) {
return undefined
}
const element = snapshot?.elements?.find((candidate) => candidate.index === index)
if (!element) {
throw new RuntimeClientError(
'element_not_found',
`element ${index} is not in the current cached snapshot; run get-app-state again and use a fresh element index`
)
}
return element
}
function snapshotCacheKeys(
query: string,
snapshot: BridgeSnapshot,
params: Record<string, unknown>
): string[] {
const namespace = snapshotNamespace(params)
const keys = new Set<string>()
for (const key of [
query,
snapshot.app.name,
snapshot.app.bundleId,
snapshot.app.bundleIdentifier,
String(snapshot.app.pid),
...snapshotKeysForWindow(query, snapshot),
...snapshotKeysForWindow(snapshot.app.name, snapshot),
...(snapshot.app.bundleId ? snapshotKeysForWindow(snapshot.app.bundleId, snapshot) : []),
...(snapshot.app.bundleIdentifier
? snapshotKeysForWindow(snapshot.app.bundleIdentifier, snapshot)
: []),
...snapshotKeysForWindowIndex(query, params),
...snapshotKeysForWindowIndex(snapshot.app.name, params),
...(snapshot.app.bundleId ? snapshotKeysForWindowIndex(snapshot.app.bundleId, params) : []),
...(snapshot.app.bundleIdentifier
? snapshotKeysForWindowIndex(snapshot.app.bundleIdentifier, params)
: [])
]) {
if (!key) {
continue
}
if (!isExplicitSnapshotNamespace(namespace)) {
keys.add(key.toLowerCase())
}
keys.add(namespacedSnapshotKey(namespace, key))
}
return [...keys]
}
function snapshotKeysForWindow(query: string, snapshot: BridgeSnapshot): string[] {
return snapshot.windowId === null || snapshot.windowId === undefined
? []
: [snapshotWindowKey(query, snapshot.windowId)]
}
function snapshotWindowKey(query: string, windowId: number): string {
return `${query.toLowerCase()}#window:${windowId}`
}
function snapshotKeysForWindowIndex(query: string, params: Record<string, unknown>): string[] {
const windowIndex = optionalNumberParam(params, 'windowIndex')
return windowIndex === undefined ? [] : [snapshotWindowIndexKey(query, windowIndex)]
}
function snapshotWindowIndexKey(query: string, windowIndex: number): string {
return `${query.toLowerCase()}#window-index:${windowIndex}`
}
function snapshotNamespace(params: Record<string, unknown>): string {
const session = optionalStringParam(params, 'session')
const worktree = optionalStringParam(params, 'worktree')
return session ? `session:${session}` : worktree ? `worktree:${worktree}` : 'default'
}
function namespacedSnapshotKey(namespace: string, key: string): string {
return `${namespace}:${key.toLowerCase()}`
}
function isExplicitSnapshotNamespace(namespace: string): boolean {
return namespace !== 'default'
}
function mapBridgeError(message: string): RuntimeClientError {
const text = message.trim() || 'desktop provider failed'
if (/appNotFound|app not found/i.test(text)) {
return new RuntimeClientError('app_not_found', text)
}
if (/appBlocked|app blocked/i.test(text)) {
return new RuntimeClientError('app_blocked', text)
}
if (/unsupported capability|hotkey.*require|paste_text requires/i.test(text)) {
return new RuntimeClientError('unsupported_capability', text)
}
if (/ModuleNotFoundError: No module named 'gi'|PyGObject|python3-gi/i.test(text)) {
return new RuntimeClientError(
'unsupported_capability',
'Linux Computer Use requires python3-gi and AT-SPI packages. Install python3-gi gir1.2-atspi-2.0 at-spi2-core, then retry.'
)
}
if (/not a valid secondary action|action.*not supported/i.test(text)) {
return new RuntimeClientError('action_not_supported', text)
}
if (/value is not settable|not settable/i.test(text)) {
return new RuntimeClientError('value_not_settable', text)
}
if (/stale element|fresh element index/i.test(text)) {
return new RuntimeClientError('element_not_found', text)
}
if (/windowStale|window stale/i.test(text)) {
return new RuntimeClientError('window_stale', text)
}
if (/No top-level|No .*window|window/i.test(text)) {
return new RuntimeClientError('window_not_found', text)
}
if (/permission|desktop session|DBUS|XDG_RUNTIME_DIR|AT-SPI/i.test(text)) {
return new RuntimeClientError('permission_denied', text)
}
if (/element|element_index/i.test(text)) {
return new RuntimeClientError('element_not_found', text)
}
return new RuntimeClientError('accessibility_error', text)
}
function requiredPlatform(): DesktopScriptPlatform {
@@ -813,25 +272,3 @@ function requiredScriptPath(): string {
}
return scriptPath
}
function stringParam(params: Record<string, unknown>, key: string): string {
const value = params[key]
if (typeof value !== 'string' || value.length === 0) {
throw new RuntimeClientError('invalid_argument', `missing ${key}`)
}
return value
}
function optionalStringParam(params: Record<string, unknown>, key: string): string | undefined {
const value = params[key]
return typeof value === 'string' ? value : undefined
}
function optionalNumberParam(params: Record<string, unknown>, key: string): number | undefined {
const value = params[key]
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
}
function sanitize(value: string): string {
return value.replaceAll('\n', ' ').replaceAll('\r', ' ')
}
@@ -0,0 +1,159 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
createDesktopScriptProviderClient,
expectDesktopProviderSubprocessStarted,
mockDesktopProviderSubprocessThatIgnoresTimeout,
mockBridgeResponse,
resetDesktopScriptProviderTestHarness,
sampleBridgeSnapshot,
sampleCapabilities
} from './desktop-script-provider-test-harness'
describe('DesktopScriptProviderClient errors and capabilities', () => {
afterEach(resetDesktopScriptProviderTestHarness)
it('explains screenshot capture failures while keeping accessibility state usable', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
screenshotPngBase64: null
}
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).resolves.toMatchObject({
snapshot: {
elementCount: 1
},
screenshotStatus: {
state: 'failed',
code: 'screenshot_failed',
message: expect.stringContaining('--no-screenshot')
}
})
})
it('preserves desktop provider screenshot failure reasons', async () => {
mockBridgeResponse({
ok: true,
snapshot: {
...sampleBridgeSnapshot('Text Editor', 'initial'),
screenshotPngBase64: null,
screenshotError: {
code: 'screenshot_failed',
message:
'screenshot exceeded the computer-use payload cap after downscaling; retry with --no-screenshot or target a smaller window'
}
}
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Text Editor' })).resolves.toMatchObject({
snapshot: {
elementCount: 1
},
screenshotStatus: {
state: 'failed',
code: 'screenshot_failed',
message: expect.stringContaining('payload cap')
}
})
})
it('normalizes list-windows responses after provider handshake', async () => {
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 100 },
windows: [
{
index: 0,
app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 100 },
id: 99,
title: 'Document',
x: 10,
y: 20,
width: 300,
height: 200,
isMinimized: false,
isOffscreen: false,
screenIndex: null,
platform: { backend: 'at-spi' }
}
]
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.listWindows({ app: 'Text Editor' })).resolves.toMatchObject({
app: { name: 'Text Editor', bundleId: 'Text Editor', pid: 100 },
windows: [{ index: 0, id: 99, title: 'Document' }]
})
})
it('maps bridge app errors to RuntimeClientError codes', async () => {
mockBridgeResponse({ ok: false, error: 'appNotFound("Missing")' })
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
await expect(client.snapshot({ app: 'Missing' })).rejects.toMatchObject({
code: 'app_not_found'
})
})
it('maps blocked app bridge errors to a policy error', async () => {
mockBridgeResponse({ ok: false, error: 'appBlocked("1Password")' })
const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1')
await expect(client.snapshot({ app: '1Password' })).rejects.toMatchObject({
code: 'app_blocked'
})
})
it('rejects when the desktop provider subprocess ignores the exec timeout', async () => {
vi.useFakeTimers()
const kill = vi.fn()
const once = vi.fn()
mockDesktopProviderSubprocessThatIgnoresTimeout({ kill, once })
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const promise = client.listApps()
let settled = false
void promise.catch(() => {
settled = true
})
await vi.waitFor(expectDesktopProviderSubprocessStarted, { timeout: 1_000 })
await vi.advanceTimersByTimeAsync(30_001)
await vi.runOnlyPendingTimersAsync()
expect(settled).toBe(true)
expect(kill).toHaveBeenCalledWith('SIGTERM')
await expect(promise).rejects.toMatchObject({ code: 'action_timeout' })
})
it('force-kills a timed-out desktop provider subprocess that has not exited', async () => {
vi.useFakeTimers()
const kill = vi.fn()
const once = vi.fn()
mockDesktopProviderSubprocessThatIgnoresTimeout({ kill, once })
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const promise = client.listApps().catch(() => undefined)
await vi.waitFor(expectDesktopProviderSubprocessStarted, { timeout: 1_000 })
await vi.advanceTimersByTimeAsync(30_001)
expect(kill).toHaveBeenCalledWith('SIGTERM')
await vi.advanceTimersByTimeAsync(1_000)
expect(kill).toHaveBeenCalledWith('SIGKILL')
await promise
})
})
@@ -0,0 +1,25 @@
import { RuntimeClientError } from './runtime-client-error'
export function stringParam(params: Record<string, unknown>, key: string): string {
const value = params[key]
if (typeof value !== 'string' || value.length === 0) {
throw new RuntimeClientError('invalid_argument', `missing ${key}`)
}
return value
}
export function optionalStringParam(
params: Record<string, unknown>,
key: string
): string | undefined {
const value = params[key]
return typeof value === 'string' ? value : undefined
}
export function optionalNumberParam(
params: Record<string, unknown>,
key: string
): number | undefined {
const value = params[key]
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
}
@@ -0,0 +1,154 @@
import { expect, vi } from 'vitest'
const { execFileMock, operationFiles, mkdtempMock, rmMock, writeFileMock } = vi.hoisted(() => {
const files = new Map<string, string>()
return {
execFileMock: vi.fn(),
operationFiles: files,
mkdtempMock: vi.fn(async (prefix: string) => `${prefix}${files.size}`),
rmMock: vi.fn(async () => undefined),
writeFileMock: vi.fn(async (filePath: string, data: string | Buffer) => {
files.set(filePath, Buffer.isBuffer(data) ? data.toString('utf8') : data)
})
}
})
vi.mock('child_process', () => ({
execFile: execFileMock
}))
vi.mock('fs/promises', () => ({
mkdtemp: mkdtempMock,
rm: rmMock,
writeFile: writeFileMock
}))
export async function createDesktopScriptProviderClient(
platform: 'linux' | 'windows',
executablePath: string
) {
const { DesktopScriptProviderClient } = await import('./desktop-script-provider-client')
return new DesktopScriptProviderClient(platform, executablePath)
}
export function resetDesktopScriptProviderTestHarness(): void {
vi.useRealTimers()
execFileMock.mockReset()
operationFiles.clear()
mkdtempMock.mockClear()
rmMock.mockClear()
writeFileMock.mockClear()
}
export function mockDesktopProviderSubprocessThatIgnoresTimeout({
kill,
once
}: {
kill: (signal: string) => void
once: () => void
}): void {
execFileMock.mockImplementationOnce(() => ({ kill, once }) as never)
}
export function expectDesktopProviderSubprocessStarted(): void {
expect(execFileMock).toHaveBeenCalled()
}
export function expectDesktopProviderSubprocessStartCount(count: number): void {
expect(execFileMock).toHaveBeenCalledTimes(count)
}
export function mockBridgeResponse(
response: unknown,
inspectOperation?: (operation: Record<string, unknown>) => void
): void {
execFileMock.mockImplementationOnce((_command, _args, _options, callback) => {
const operationPath = _args?.at(-1)
if (inspectOperation && typeof operationPath === 'string') {
const operation = operationFiles.get(operationPath)
if (!operation) {
throw new Error(`Missing mocked operation file: ${operationPath}`)
}
inspectOperation(JSON.parse(operation) as Record<string, unknown>)
}
const done = callback as (error: Error | null, stdout: string, stderr: string) => void
done(null, JSON.stringify(response), '')
return null as never
})
}
export function sampleBridgeSnapshot(name: string, value: string) {
return {
app: { name, bundleIdentifier: name, pid: 100 },
snapshotId: 'snap-test',
windowTitle: name,
windowId: 99,
windowBounds: { x: 10, y: 20, width: 300, height: 200 },
screenshotPngBase64: 'iVBORw0KGgo=',
coordinateSpace: 'window',
truncation: { truncated: false, maxNodes: 1200, maxDepth: 64, maxDepthReached: false },
treeLines: [`0 text entry area, Value: ${value}`],
focusedSummary: 'text entry area',
elements: [
{
index: 0,
runtimeId: [0, 0],
name: 'Body',
controlType: 'text',
localizedControlType: 'text entry area',
value,
frame: { x: 1, y: 2, width: 100, height: 20 },
actions: ['SetValue']
}
]
}
}
export function sampleCapabilities(actions: Partial<Record<string, boolean>> = {}) {
return {
platform: 'linux',
provider: 'orca-computer-use-linux',
providerVersion: '1.0.0',
protocolVersion: 1,
supports: {
apps: { list: true, bundleIds: false, pids: true },
windows: {
list: true,
targetById: true,
targetByIndex: true,
focus: false,
moveResize: false
},
observation: {
screenshot: true,
annotatedScreenshot: false,
elementFrames: true,
ocr: false
},
actions: {
click: true,
typeText: true,
pressKey: true,
hotkey: true,
pasteText: true,
scroll: true,
drag: true,
setValue: true,
performAction: true,
...actions
},
surfaces: { menus: false, dialogs: false, dock: false, menubar: false }
}
}
}
export function sampleListWindowsCapabilities() {
return sampleCapabilities({
hotkey: false,
pasteText: false
})
}
export function publicSnapshotKeys(snapshot: unknown): string[] {
return Object.keys(snapshot as Record<string, unknown>).sort()
}
@@ -0,0 +1,148 @@
import type {
ComputerActionMetadata,
ComputerProviderCapabilities
} from '../../shared/runtime-types'
export type NativeMethod =
| 'handshake'
| 'listApps'
| 'listWindows'
| 'getAppState'
| 'click'
| 'performSecondaryAction'
| 'scroll'
| 'drag'
| 'typeText'
| 'pressKey'
| 'hotkey'
| 'pasteText'
| 'setValue'
export type NativeActionMethod = Exclude<
NativeMethod,
'handshake' | 'listApps' | 'listWindows' | 'getAppState'
>
export type BridgeFrame = {
x: number
y: number
width: number
height: number
}
export type BridgeElement = {
index: number
runtimeId?: unknown
automationId?: string
name?: string
controlType?: string
localizedControlType?: string
className?: string
value?: string
isSelected?: boolean
nativeWindowHandle?: number
frame?: BridgeFrame | null
actions?: string[]
}
export type BridgeSnapshot = {
snapshotId?: string
app: {
name: string
bundleIdentifier?: string
bundleId?: string
pid: number
}
windowTitle?: string
windowId?: number | null
windowIndex?: number | null
windowBounds?: BridgeFrame | null
screenshotPngBase64?: string | null
screenshotWidth?: number | null
screenshotHeight?: number | null
screenshotScale?: number | null
screenshotError?: {
code?: string | null
message?: string | null
} | null
coordinateSpace?: 'window'
truncation?: {
truncated?: boolean
maxNodes?: number
maxDepth?: number
maxDepthReached?: boolean
}
treeLines?: string[]
focusedSummary?: string | null
focusedElementId?: number | null
selectedText?: string | null
elements?: BridgeElement[]
}
export type BridgeWindow = {
index: number
app: {
name: string
bundleIdentifier?: string | null
bundleId?: string | null
pid: number
}
id?: number | null
title: string
x?: number | null
y?: number | null
width: number
height: number
isMinimized?: boolean | null
isOffscreen?: boolean | null
screenIndex?: number | null
platform?: Record<string, unknown>
}
export type BridgeResponse = {
ok: boolean
error?: string
capabilities?: ComputerProviderCapabilities
apps?: {
name: string
bundleIdentifier?: string | null
bundleId?: string | null
pid: number
}[]
app?: {
name: string
bundleIdentifier?: string | null
bundleId?: string | null
pid: number
}
windows?: BridgeWindow[]
snapshot?: BridgeSnapshot
action?: ComputerActionMetadata
}
export type BridgeRequest = {
tool: string
app?: string
element?: BridgeElement
fromElement?: BridgeElement
toElement?: BridgeElement
x?: number
y?: number
from_x?: number
from_y?: number
to_x?: number
to_y?: number
click_count?: number
mouse_button?: string
action?: string
direction?: string
pages?: number
text?: string
key?: string
value?: string
windowBounds?: BridgeFrame | null
windowId?: number
windowIndex?: number
noScreenshot?: boolean
restoreWindow?: boolean
}
@@ -0,0 +1,200 @@
import { optionalNumberParam, optionalStringParam } from './desktop-script-provider-params'
import type { BridgeSnapshot } from './desktop-script-provider-types'
export const MAX_CACHED_DESKTOP_SNAPSHOTS = 32
// Why: cached element frames and provider IDs are follow-up hints, not durable
// state; delayed agents should refresh instead of acting on old UI geometry.
export const MAX_CACHED_DESKTOP_SNAPSHOT_AGE_MS = 2 * 60 * 1000
export type CachedSnapshotEntry = {
snapshot: BridgeSnapshot
keys: string[]
createdAtMs: number
}
export function snapshotCacheKeys(
query: string,
snapshot: BridgeSnapshot,
params: Record<string, unknown>
): string[] {
const namespace = snapshotNamespace(params)
const pidKeys = snapshotPidKeys(snapshot.app.pid)
const keys = new Set<string>()
if (snapshot.windowId !== null && snapshot.windowId !== undefined) {
keys.add(canonicalWindowIdKey(snapshot.windowId))
keys.add(namespacedSnapshotKey(namespace, canonicalWindowIdKey(snapshot.windowId)))
}
const resolvedWindowIndex = optionalNumberParam(params, 'windowIndex') ?? snapshot.windowIndex
if (resolvedWindowIndex !== null && resolvedWindowIndex !== undefined) {
keys.add(canonicalWindowIndexKey(resolvedWindowIndex))
keys.add(namespacedSnapshotKey(namespace, canonicalWindowIndexKey(resolvedWindowIndex)))
}
for (const key of [
query,
snapshot.app.name,
snapshot.app.bundleId,
snapshot.app.bundleIdentifier,
...pidKeys,
...snapshotKeysForWindow(query, snapshot),
...snapshotKeysForWindow(snapshot.app.name, snapshot),
...(snapshot.app.bundleId ? snapshotKeysForWindow(snapshot.app.bundleId, snapshot) : []),
...(snapshot.app.bundleIdentifier
? snapshotKeysForWindow(snapshot.app.bundleIdentifier, snapshot)
: []),
...pidKeys.flatMap((pidKey) => snapshotKeysForWindow(pidKey, snapshot)),
...snapshotKeysForWindowIndex(query, snapshot, params),
...snapshotKeysForWindowIndex(snapshot.app.name, snapshot, params),
...(snapshot.app.bundleId
? snapshotKeysForWindowIndex(snapshot.app.bundleId, snapshot, params)
: []),
...(snapshot.app.bundleIdentifier
? snapshotKeysForWindowIndex(snapshot.app.bundleIdentifier, snapshot, params)
: []),
...pidKeys.flatMap((pidKey) => snapshotKeysForWindowIndex(pidKey, snapshot, params))
]) {
if (!key) {
continue
}
if (!isExplicitSnapshotNamespace(namespace)) {
keys.add(key.toLowerCase())
}
keys.add(namespacedSnapshotKey(namespace, key))
}
return [...keys]
}
function snapshotKeysForWindow(query: string, snapshot: BridgeSnapshot): string[] {
return snapshot.windowId === null || snapshot.windowId === undefined
? []
: [snapshotWindowKey(query, snapshot.windowId)]
}
export function snapshotWindowKey(query: string, windowId: number): string {
return `${query.toLowerCase()}#window:${windowId}`
}
export function canonicalWindowIdKey(windowId: number): string {
return `window-id:${windowId}`
}
export function canonicalWindowIndexKey(windowIndex: number): string {
return `window-index:${windowIndex}`
}
function snapshotKeysForWindowIndex(
query: string,
snapshot: BridgeSnapshot,
params: Record<string, unknown>
): string[] {
const windowIndex = optionalNumberParam(params, 'windowIndex') ?? snapshot.windowIndex
return windowIndex === null || windowIndex === undefined
? []
: [snapshotWindowIndexKey(query, windowIndex)]
}
export function snapshotWindowIndexKey(query: string, windowIndex: number): string {
return `${query.toLowerCase()}#window-index:${windowIndex}`
}
export function snapshotNamespace(params: Record<string, unknown>): string {
const session = optionalStringParam(params, 'session')
const worktree = optionalStringParam(params, 'worktree')
return session ? `session:${session}` : worktree ? `worktree:${worktree}` : 'default'
}
export function namespacedSnapshotKey(namespace: string, key: string): string {
return `${namespace}:${key.toLowerCase()}`
}
export function staleWindowTargetKeys(
query: string,
params: Record<string, unknown>,
snapshot: BridgeSnapshot | null
): string[] {
const namespace = snapshotNamespace(params)
const windowId = optionalNumberParam(params, 'windowId')
const windowIndex = optionalNumberParam(params, 'windowIndex')
if (windowId === undefined && windowIndex === undefined) {
return []
}
const keys = new Set<string>()
if (windowId !== undefined) {
keys.add(canonicalWindowIdKey(windowId))
keys.add(namespacedSnapshotKey(namespace, canonicalWindowIdKey(windowId)))
}
if (windowIndex !== undefined) {
keys.add(canonicalWindowIndexKey(windowIndex))
keys.add(namespacedSnapshotKey(namespace, canonicalWindowIndexKey(windowIndex)))
}
for (const appKey of snapshotAppKeys(query, snapshot)) {
const targetKey =
windowId !== undefined
? snapshotWindowKey(appKey, windowId)
: snapshotWindowIndexKey(appKey, windowIndex!)
if (!isExplicitSnapshotNamespace(namespace)) {
keys.add(targetKey.toLowerCase())
}
keys.add(namespacedSnapshotKey(namespace, targetKey))
}
return [...keys]
}
export function lookupCachedSnapshotKey(
app: string,
params: Record<string, unknown>,
windowId: number | undefined,
windowIndex: number | undefined
): string[] {
const namespace = snapshotNamespace(params)
const keys: string[] = []
if (windowId !== undefined) {
keys.push(
namespacedSnapshotKey(namespace, canonicalWindowIdKey(windowId)),
namespacedSnapshotKey(namespace, snapshotWindowKey(app, windowId))
)
if (!isExplicitSnapshotNamespace(namespace)) {
keys.push(canonicalWindowIdKey(windowId), snapshotWindowKey(app, windowId))
}
}
if (windowIndex !== undefined) {
keys.push(
namespacedSnapshotKey(namespace, canonicalWindowIndexKey(windowIndex)),
namespacedSnapshotKey(namespace, snapshotWindowIndexKey(app, windowIndex))
)
if (!isExplicitSnapshotNamespace(namespace)) {
keys.push(canonicalWindowIndexKey(windowIndex), snapshotWindowIndexKey(app, windowIndex))
}
}
keys.push(namespacedSnapshotKey(namespace, app))
if (!isExplicitSnapshotNamespace(namespace)) {
keys.push(app.toLowerCase())
}
return keys
}
function snapshotAppKeys(query: string, snapshot: BridgeSnapshot | null): string[] {
return [
query,
snapshot?.app.name,
snapshot?.app.bundleId,
snapshot?.app.bundleIdentifier,
...(snapshot ? snapshotPidKeys(snapshot.app.pid) : [])
].filter((value): value is string => typeof value === 'string' && value.length > 0)
}
function snapshotPidKeys(pid: number): string[] {
if (!Number.isInteger(pid) || pid <= 0) {
return []
}
return [snapshotPidSelector(pid), String(pid)]
}
function snapshotPidSelector(pid: number): string {
return `pid:${pid}`
}
export function isExplicitSnapshotNamespace(namespace: string): boolean {
return namespace !== 'default'
}
@@ -0,0 +1,154 @@
import type { ComputerSnapshotResult } from '../../shared/runtime-types'
import { RuntimeClientError } from './runtime-client-error'
import type { BridgeResponse, BridgeSnapshot, BridgeWindow } from './desktop-script-provider-types'
export function renderSnapshot(
snapshot: BridgeSnapshot,
noScreenshot: boolean
): ComputerSnapshotResult {
const bounds = snapshot.windowBounds
const treeText = renderTreeText(snapshot)
const focusedElementId = normalizedFocusedElementId(snapshot)
// Why: Linux/Windows providers may downscale screenshots to cap IPC payloads,
// while window bounds remain the unscaled coordinate space for actions.
const screenshotWidth =
positiveRoundedNumber(snapshot.screenshotWidth) ?? Math.max(1, Math.round(bounds?.width ?? 1))
const screenshotHeight =
positiveRoundedNumber(snapshot.screenshotHeight) ?? Math.max(1, Math.round(bounds?.height ?? 1))
const screenshotScale = positiveNumber(snapshot.screenshotScale) ?? 1
const screenshot = snapshot.screenshotPngBase64
? {
data: snapshot.screenshotPngBase64,
format: 'png' as const,
width: screenshotWidth,
height: screenshotHeight,
scale: screenshotScale
}
: null
return {
snapshot: {
// Why: bridge elements can be large; keep them cached internally for actions
// instead of returning duplicated metadata in every agent-facing snapshot.
id: snapshot.snapshotId ?? fallbackSnapshotId(snapshot),
app: {
name: snapshot.app.name,
bundleId: snapshot.app.bundleId ?? snapshot.app.bundleIdentifier ?? null,
pid: snapshot.app.pid
},
window: {
title: snapshot.windowTitle ?? snapshot.app.name,
id: snapshot.windowId ?? null,
index: snapshot.windowIndex ?? null,
x: bounds ? Math.round(bounds.x) : null,
y: bounds ? Math.round(bounds.y) : null,
width: Math.max(0, Math.round(bounds?.width ?? 0)),
height: Math.max(0, Math.round(bounds?.height ?? 0)),
isMinimized: null,
isOffscreen: null,
screenIndex: null
},
coordinateSpace: snapshot.coordinateSpace ?? 'window',
treeText,
elementCount: snapshot.elements?.length ?? 0,
focusedElementId,
truncation: {
truncated: snapshot.truncation?.truncated === true,
maxNodes: snapshot.truncation?.maxNodes,
maxDepth: snapshot.truncation?.maxDepth,
maxDepthReached: snapshot.truncation?.maxDepthReached === true
}
},
screenshot,
screenshotStatus: screenshot
? {
state: 'captured',
metadata: { engine: 'unknown', windowId: snapshot.windowId ?? null }
}
: noScreenshot
? { state: 'skipped', reason: 'no_screenshot_flag' }
: desktopScreenshotFailureStatus(snapshot)
}
}
function desktopScreenshotFailureStatus(
snapshot: BridgeSnapshot
): ComputerSnapshotResult['screenshotStatus'] {
if (snapshot.screenshotError?.message) {
return {
state: 'failed',
code: 'screenshot_failed',
message: snapshot.screenshotError.message
}
}
return {
state: 'failed',
code: 'screenshot_failed',
message:
'desktop provider returned no image; grant screen capture permission or pass --no-screenshot to inspect accessibility state only.'
}
}
export function snapshotWithoutScreenshot(snapshot: BridgeSnapshot): BridgeSnapshot {
return snapshot.screenshotPngBase64 ? { ...snapshot, screenshotPngBase64: null } : snapshot
}
function normalizedFocusedElementId(snapshot: BridgeSnapshot): number | null {
const focusedElementId = snapshot.focusedElementId
if (focusedElementId === null || focusedElementId === undefined) {
return null
}
return snapshot.elements?.some((element) => element.index === focusedElementId) === true
? focusedElementId
: null
}
function positiveNumber(value: number | null | undefined): number | null {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null
}
function positiveRoundedNumber(value: number | null | undefined): number | null {
const numberValue = positiveNumber(value)
return numberValue === null ? null : Math.max(1, Math.round(numberValue))
}
function fallbackSnapshotId(snapshot: BridgeSnapshot): string {
const appRef = snapshot.app.bundleId ?? snapshot.app.bundleIdentifier ?? snapshot.app.name
const windowRef =
snapshot.windowId !== null && snapshot.windowId !== undefined
? String(snapshot.windowId)
: snapshot.windowIndex !== null && snapshot.windowIndex !== undefined
? `window-index:${snapshot.windowIndex}`
: 'window'
return `${appRef}:${snapshot.app.pid}:${windowRef}`
}
function renderTreeText(snapshot: BridgeSnapshot): string {
const appRef = snapshot.app.bundleId ?? snapshot.app.bundleIdentifier ?? snapshot.app.name
const lines = [
`App=${appRef} (pid ${snapshot.app.pid})`,
`Window: "${sanitize(snapshot.windowTitle ?? snapshot.app.name)}", App: ${sanitize(snapshot.app.name)}.`,
'',
...(snapshot.treeLines ?? [])
]
if (snapshot.selectedText) {
lines.push('', `Selected text: [${sanitize(snapshot.selectedText)}]`)
} else if (snapshot.focusedSummary) {
lines.push('', `The focused UI element is ${sanitize(snapshot.focusedSummary)}.`)
}
return lines.join('\n')
}
export function normalizeBridgeApp(app: BridgeResponse['app'] | BridgeWindow['app'] | undefined) {
if (!app) {
throw new RuntimeClientError('accessibility_error', 'desktop provider returned no app')
}
return {
name: app.name,
bundleId: app.bundleId ?? app.bundleIdentifier ?? null,
pid: app.pid
}
}
function sanitize(value: string): string {
return value.replaceAll('\n', ' ').replaceAll('\r', ' ')
}
@@ -0,0 +1,99 @@
import { optionalNumberParam } from './desktop-script-provider-params'
import type { BridgeSnapshot } from './desktop-script-provider-types'
import {
lookupCachedSnapshotKey,
MAX_CACHED_DESKTOP_SNAPSHOT_AGE_MS,
MAX_CACHED_DESKTOP_SNAPSHOTS,
snapshotCacheKeys,
type CachedSnapshotEntry,
staleWindowTargetKeys
} from './desktop-script-snapshot-cache'
import { snapshotWithoutScreenshot } from './desktop-script-snapshot-rendering'
export class DesktopScriptSnapshotStore {
readonly snapshots = new Map<string, BridgeSnapshot>()
private readonly snapshotEntries: CachedSnapshotEntry[] = []
clear(): void {
this.snapshots.clear()
this.snapshotEntries.length = 0
}
remember(query: string, snapshot: BridgeSnapshot, params: Record<string, unknown>): void {
const keys = snapshotCacheKeys(query, snapshot, params)
if (keys.length === 0) {
return
}
// Why: cached snapshots only supply element identity for follow-up actions;
// retaining PNG base64 across agent loops grows the long-lived sidecar.
const cachedSnapshot = snapshotWithoutScreenshot(snapshot)
const entry = { snapshot: cachedSnapshot, keys, createdAtMs: Date.now() }
this.snapshotEntries.push(entry)
for (const key of keys) {
this.snapshots.set(key, cachedSnapshot)
}
this.prune()
}
current(
app: string,
windowId: number | undefined,
params: Record<string, unknown>
): BridgeSnapshot | null {
this.prune()
const windowIndex = optionalNumberParam(params, 'windowIndex')
const keys = lookupCachedSnapshotKey(app, params, windowId, windowIndex)
const hasExplicitWindowTarget = windowId !== undefined || windowIndex !== undefined
for (const key of keys) {
if (
hasExplicitWindowTarget &&
!key.includes('#window') &&
!key.includes('window-id:') &&
!key.includes('window-index:')
) {
continue
}
const cached = this.snapshots.get(key)
if (cached) {
return cached
}
}
return null
}
forgetWindowTarget(
query: string,
params: Record<string, unknown>,
snapshot: BridgeSnapshot | null
): void {
const keys = staleWindowTargetKeys(query, params, snapshot)
for (const key of keys) {
this.snapshots.delete(key)
}
}
private prune(): void {
while (
this.snapshotEntries.length > 0 &&
(this.snapshotEntries.length > MAX_CACHED_DESKTOP_SNAPSHOTS ||
this.isExpired(this.snapshotEntries[0]))
) {
const expired = this.snapshotEntries.shift()
if (!expired) {
return
}
for (const key of expired.keys) {
// Why: newer snapshots can reuse the same alias; only remove aliases
// that still point at the large snapshot payload being evicted.
if (this.snapshots.get(key) === expired.snapshot) {
this.snapshots.delete(key)
}
}
}
}
private isExpired(entry: CachedSnapshotEntry): boolean {
return Date.now() - entry.createdAtMs > MAX_CACHED_DESKTOP_SNAPSHOT_AGE_MS
}
}
@@ -0,0 +1,221 @@
import { execFileSync, spawn, spawnSync } from 'child_process'
import { mkdtemp, readFile, rm, stat } from 'fs/promises'
import { join } from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const resolveHelperAppPathMock = vi.hoisted(() => vi.fn())
const resolveHelperExecutablePathMock = vi.hoisted(() => vi.fn())
const permissionStatusTempDir = '/tmp/orca-computer-use-permissions-test'
const permissionStatusPath = join(permissionStatusTempDir, 'status.json')
vi.mock('child_process', () => ({
execFileSync: vi.fn(),
spawn: vi.fn(() => {
const child = {
stdout: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
stderr: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
on: vi.fn((event: string, callback: (status: number) => void) => {
if (event === 'close') {
queueMicrotask(() => callback(0))
}
return child
}),
off: vi.fn(() => child),
unref: vi.fn()
}
return child
}),
spawnSync: vi.fn()
}))
vi.mock('fs/promises', () => ({
mkdtemp: vi.fn(),
readFile: vi.fn(),
rm: vi.fn(),
stat: vi.fn()
}))
vi.mock('./macos-native-provider-paths', () => ({
resolveMacOSComputerUseAppPath: resolveHelperAppPathMock,
resolveMacOSComputerUseExecutablePath: resolveHelperExecutablePathMock
}))
describe('getComputerUsePermissionStatus', () => {
const originalPlatform = process.platform
beforeEach(() => {
vi.mocked(spawn).mockClear()
vi.mocked(spawnSync).mockClear()
vi.mocked(execFileSync).mockReset()
vi.mocked(mkdtemp).mockReset()
vi.mocked(readFile).mockReset()
vi.mocked(rm).mockReset()
vi.mocked(stat).mockReset()
resolveHelperAppPathMock.mockReset()
resolveHelperExecutablePathMock.mockReset()
resolveHelperAppPathMock.mockReturnValue('/Applications/Orca Computer Use.app')
resolveHelperExecutablePathMock.mockReturnValue(
'/Applications/Orca Computer Use.app/Contents/MacOS/orca-computer-use-macos'
)
vi.mocked(mkdtemp).mockResolvedValue(permissionStatusTempDir)
vi.mocked(stat).mockResolvedValue({} as Awaited<ReturnType<typeof stat>>)
mockPermissionStatus('{"accessibility":"granted","screenshots":"granted"}')
setPlatform('darwin')
})
afterEach(() => {
vi.useRealTimers()
setPlatform(originalPlatform)
})
it('wraps permission status helper launch failures', async () => {
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
const child = {
stdout: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
stderr: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
on: vi.fn((event: string, callback: (error: Error) => void) => {
if (event === 'error') {
queueMicrotask(() => callback(new Error('spawn ENOENT /private/path')))
}
return child
}),
off: vi.fn(() => child),
unref: vi.fn()
}
vi.mocked(spawn).mockImplementationOnce(() => child as unknown as ReturnType<typeof spawn>)
await expect(getComputerUsePermissionStatus()).rejects.toMatchObject({
name: 'RuntimeClientError',
code: 'accessibility_error',
message: 'Could not check permissions: failed to launch helper'
})
expect(rm).toHaveBeenCalledWith(permissionStatusTempDir, {
recursive: true,
force: true
})
})
it('removes permission status helper listeners after close', async () => {
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
const child = {
stdout: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
stderr: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
on: vi.fn((event: string, callback: (status: number) => void) => {
if (event === 'close') {
queueMicrotask(() => callback(0))
}
return child
}),
off: vi.fn(() => child),
unref: vi.fn()
}
vi.mocked(spawn).mockImplementationOnce(() => child as unknown as ReturnType<typeof spawn>)
await expect(getComputerUsePermissionStatus()).resolves.toMatchObject({
helperUnavailableReason: null
})
expect(child.stdout.off).toHaveBeenCalledWith('data', expect.any(Function))
expect(child.stderr.off).toHaveBeenCalledWith('data', expect.any(Function))
expect(child.off).toHaveBeenCalledWith('error', expect.any(Function))
expect(child.off).toHaveBeenCalledWith('close', expect.any(Function))
})
it('times out when the permission status helper launch never closes', async () => {
vi.useFakeTimers()
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
const child = {
stdout: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
stderr: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
on: vi.fn(() => child),
off: vi.fn(() => child),
kill: vi.fn(),
unref: vi.fn()
}
vi.mocked(spawn).mockImplementationOnce(() => child as unknown as ReturnType<typeof spawn>)
let settled = false
const statusPromise = getComputerUsePermissionStatus().then(
(status) => {
settled = true
return status
},
(error: unknown) => {
settled = true
throw error
}
)
const rejection = expect(statusPromise).rejects.toMatchObject({
name: 'RuntimeClientError',
code: 'accessibility_error',
message: 'Timed out launching permission helper'
})
await vi.advanceTimersByTimeAsync(5000)
expect(settled).toBe(true)
await rejection
expect(child.kill).toHaveBeenCalled()
expect(rm).toHaveBeenCalledWith(permissionStatusTempDir, {
recursive: true,
force: true
})
})
it('reads permission status through the helper app identity', async () => {
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
mockPermissionStatus('{"accessibility":"granted","screenshots":"not-granted"}')
await expect(getComputerUsePermissionStatus()).resolves.toEqual({
platform: 'darwin',
helperAppPath: '/Applications/Orca Computer Use.app',
helperUnavailableReason: null,
permissions: [
{ id: 'accessibility', status: 'granted' },
{ id: 'screenshots', status: 'not-granted' }
]
})
expect(spawn).toHaveBeenCalledWith(
'/usr/bin/open',
[
'-n',
'/Applications/Orca Computer Use.app',
'--args',
'--permission-status-file',
permissionStatusPath
],
{ stdio: ['ignore', 'pipe', 'pipe'] }
)
expect(spawnSync).not.toHaveBeenCalled()
expect(readFile).toHaveBeenCalledWith(permissionStatusPath, 'utf8')
expect(rm).toHaveBeenCalledWith(permissionStatusTempDir, {
recursive: true,
force: true
})
})
it('returns unavailable permission status when the helper app is missing on macOS', async () => {
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
resolveHelperAppPathMock.mockReturnValue(null)
await expect(getComputerUsePermissionStatus()).resolves.toEqual({
platform: 'darwin',
helperAppPath: null,
helperUnavailableReason: 'Orca Computer Use.app was not found',
permissions: [
{ id: 'accessibility', status: 'not-granted' },
{ id: 'screenshots', status: 'not-granted' }
]
})
expect(execFileSync).not.toHaveBeenCalled()
})
})
function mockPermissionStatus(json: string): void {
vi.mocked(spawnSync).mockReturnValue({ status: 0 } as ReturnType<typeof spawnSync>)
vi.mocked(readFile).mockResolvedValue(json)
}
function setPlatform(platform: NodeJS.Platform): void {
Object.defineProperty(process, 'platform', { configurable: true, value: platform })
}
@@ -0,0 +1,194 @@
import { spawn } from 'child_process'
import { mkdtemp, readFile, rm, stat } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import { setTimeout as delay } from 'timers/promises'
import type {
ComputerUsePermissionId,
ComputerUsePermissionStatus,
ComputerUsePermissionStatusResult
} from '../../shared/computer-use-permissions-types'
import {
resolveMacOSComputerUseAppPath,
resolveMacOSComputerUseExecutablePath
} from './macos-native-provider-paths'
import { RuntimeClientError } from './runtime-client-error'
const PERMISSION_STATUS_HELPER_LAUNCH_TIMEOUT_MS = 5_000
export function getComputerUsePermissionStatus(): Promise<ComputerUsePermissionStatusResult> {
return getComputerUsePermissionStatusAsync()
}
async function getComputerUsePermissionStatusAsync(): Promise<ComputerUsePermissionStatusResult> {
if (process.platform !== 'darwin') {
return {
platform: process.platform,
helperAppPath: null,
helperUnavailableReason: null,
permissions: [
{ id: 'accessibility', status: 'unsupported' },
{ id: 'screenshots', status: 'unsupported' }
]
}
}
const helperAppPath = resolveMacOSComputerUseAppPath()
if (!helperAppPath) {
return createUnavailablePermissionStatus('Orca Computer Use.app was not found', null)
}
const executablePath = resolveMacOSComputerUseExecutablePath()
if (!executablePath) {
return createUnavailablePermissionStatus(
`${helperAppPath}/Contents/MacOS/orca-computer-use-macos was not found`,
helperAppPath
)
}
const raw = await readPermissionStatusFromHelperApp(helperAppPath)
return {
platform: process.platform,
helperAppPath,
helperUnavailableReason: null,
permissions: [
{ id: 'accessibility', status: raw.accessibility ?? 'not-granted' },
{ id: 'screenshots', status: raw.screenshots ?? 'not-granted' }
]
}
}
function createUnavailablePermissionStatus(
reason: string,
helperAppPath: string | null
): ComputerUsePermissionStatusResult {
return {
platform: process.platform,
helperAppPath,
helperUnavailableReason: reason,
permissions: [
{ id: 'accessibility', status: 'not-granted' },
{ id: 'screenshots', status: 'not-granted' }
]
}
}
async function readPermissionStatusFromHelperApp(
helperAppPath: string
): Promise<Partial<Record<ComputerUsePermissionId, ComputerUsePermissionStatus>>> {
const tempDir = await mkdtemp(join(tmpdir(), 'orca-computer-use-permissions-'))
const statusPath = join(tempDir, 'status.json')
try {
// Why: TCC status must be checked through the helper app identity. Directly
// execing the binary can inherit the parent app's already-granted context.
await launchPermissionStatusHelper(helperAppPath, statusPath)
for (let attempt = 0; attempt < 50; attempt++) {
if (await fileExists(statusPath)) {
const output = await readFile(statusPath, 'utf8')
return JSON.parse(output) as Partial<
Record<ComputerUsePermissionId, ComputerUsePermissionStatus>
>
}
await delay(100)
}
throw new RuntimeClientError('accessibility_error', 'Timed out checking permissions')
} finally {
await rm(tempDir, { recursive: true, force: true })
}
}
function launchPermissionStatusHelper(helperAppPath: string, statusPath: string): Promise<void> {
return new Promise((resolve, reject) => {
const launch = spawn(
'/usr/bin/open',
['-n', helperAppPath, '--args', '--permission-status-file', statusPath],
{
stdio: ['ignore', 'pipe', 'pipe']
}
)
let stdout = ''
let stderr = ''
launch.stdout?.setEncoding('utf8')
launch.stderr?.setEncoding('utf8')
const onStdoutData = (chunk: string): void => {
stdout += chunk
}
const onStderrData = (chunk: string): void => {
stderr += chunk
}
let settled = false
let launchTimeout: ReturnType<typeof setTimeout> | null = null
const removeListeners = (): void => {
launch.stdout?.off('data', onStdoutData)
launch.stderr?.off('data', onStderrData)
launch.off('error', onError)
launch.off('close', onClose)
if (launchTimeout) {
clearTimeout(launchTimeout)
launchTimeout = null
}
}
const settleResolve = (): void => {
if (settled) {
return
}
settled = true
removeListeners()
resolve()
}
const settleReject = (error: Error): void => {
if (settled) {
return
}
settled = true
removeListeners()
reject(error)
}
const onError = (): void => {
settleReject(
new RuntimeClientError(
'accessibility_error',
'Could not check permissions: failed to launch helper'
)
)
}
const onClose = (status: number | null): void => {
if (status === 0) {
settleResolve()
return
}
const detail = stderr.trim() || stdout.trim() || `exit ${status ?? 'unknown'}`
settleReject(
new RuntimeClientError('accessibility_error', `Could not check permissions: ${detail}`)
)
}
const onTimeout = (): void => {
launch.kill()
settleReject(
new RuntimeClientError('accessibility_error', 'Timed out launching permission helper')
)
}
// Why: the status-file polling timeout only starts after `open` exits; if
// `open` wedges first, permission checks would otherwise stay pending.
launchTimeout = setTimeout(onTimeout, PERMISSION_STATUS_HELPER_LAUNCH_TIMEOUT_MS)
if (typeof launchTimeout.unref === 'function') {
launchTimeout.unref()
}
launch.stdout?.on('data', onStdoutData)
launch.stderr?.on('data', onStderrData)
launch.on('error', onError)
launch.on('close', onClose)
})
}
async function fileExists(path: string): Promise<boolean> {
try {
await stat(path)
return true
} catch {
return false
}
}
@@ -1,7 +1,6 @@
/* oxlint-disable max-lines -- Why: these macOS permission flows share one
mocked child_process/fs platform harness. */
import { execFileSync, spawn, spawnSync } from 'child_process'
import { mkdtemp, readFile, rm, stat } from 'fs/promises'
import { join } from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
openComputerUsePermissions,
@@ -10,6 +9,9 @@ import {
const resolveHelperAppPathMock = vi.hoisted(() => vi.fn())
const resolveHelperExecutablePathMock = vi.hoisted(() => vi.fn())
const permissionStatusTempDir = '/tmp/orca-computer-use-permissions-test'
const helperAppPath = '/Applications/Orca Computer Use.app'
const helperInfoPlistPath = join(helperAppPath, 'Contents', 'Info.plist')
vi.mock('child_process', () => ({
execFileSync: vi.fn(),
@@ -59,7 +61,7 @@ describe('openComputerUsePermissions', () => {
resolveHelperExecutablePathMock.mockReturnValue(
'/Applications/Orca Computer Use.app/Contents/MacOS/orca-computer-use-macos'
)
vi.mocked(mkdtemp).mockResolvedValue('/tmp/orca-computer-use-permissions-test')
vi.mocked(mkdtemp).mockResolvedValue(permissionStatusTempDir)
vi.mocked(stat).mockResolvedValue({} as Awaited<ReturnType<typeof stat>>)
mockPermissionStatus('{"accessibility":"granted","screenshots":"granted"}')
setPlatform('darwin')
@@ -206,139 +208,6 @@ describe('openComputerUsePermissions', () => {
)
})
it('wraps permission status helper launch failures', async () => {
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
resolveHelperAppPathMock.mockReturnValue('/Applications/Orca Computer Use.app')
const child = {
stdout: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
stderr: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
on: vi.fn((event: string, callback: (error: Error) => void) => {
if (event === 'error') {
queueMicrotask(() => callback(new Error('spawn ENOENT /private/path')))
}
return child
}),
off: vi.fn(() => child),
unref: vi.fn()
}
vi.mocked(spawn).mockImplementationOnce(() => child as unknown as ReturnType<typeof spawn>)
await expect(getComputerUsePermissionStatus()).rejects.toMatchObject({
name: 'RuntimeClientError',
code: 'accessibility_error',
message: 'Could not check permissions: failed to launch helper'
})
expect(rm).toHaveBeenCalledWith('/tmp/orca-computer-use-permissions-test', {
recursive: true,
force: true
})
})
it('removes permission status helper listeners after close', async () => {
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
resolveHelperAppPathMock.mockReturnValue('/Applications/Orca Computer Use.app')
const child = {
stdout: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
stderr: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
on: vi.fn((event: string, callback: (status: number) => void) => {
if (event === 'close') {
queueMicrotask(() => callback(0))
}
return child
}),
off: vi.fn(() => child),
unref: vi.fn()
}
vi.mocked(spawn).mockImplementationOnce(() => child as unknown as ReturnType<typeof spawn>)
await expect(getComputerUsePermissionStatus()).resolves.toMatchObject({
helperUnavailableReason: null
})
expect(child.stdout.off).toHaveBeenCalledWith('data', expect.any(Function))
expect(child.stderr.off).toHaveBeenCalledWith('data', expect.any(Function))
expect(child.off).toHaveBeenCalledWith('error', expect.any(Function))
expect(child.off).toHaveBeenCalledWith('close', expect.any(Function))
})
it('times out when the permission status helper launch never closes', async () => {
vi.useFakeTimers()
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
resolveHelperAppPathMock.mockReturnValue('/Applications/Orca Computer Use.app')
const child = {
stdout: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
stderr: { off: vi.fn(), on: vi.fn(), setEncoding: vi.fn() },
on: vi.fn(() => child),
off: vi.fn(() => child),
kill: vi.fn(),
unref: vi.fn()
}
vi.mocked(spawn).mockImplementationOnce(() => child as unknown as ReturnType<typeof spawn>)
let settled = false
const statusPromise = getComputerUsePermissionStatus().then(
(status) => {
settled = true
return status
},
(error: unknown) => {
settled = true
throw error
}
)
const rejection = expect(statusPromise).rejects.toMatchObject({
name: 'RuntimeClientError',
code: 'accessibility_error',
message: 'Timed out launching permission helper'
})
await vi.advanceTimersByTimeAsync(5000)
expect(settled).toBe(true)
await rejection
expect(child.kill).toHaveBeenCalled()
expect(rm).toHaveBeenCalledWith('/tmp/orca-computer-use-permissions-test', {
recursive: true,
force: true
})
})
it('reads permission status through the helper app identity', async () => {
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
resolveHelperAppPathMock.mockReturnValue('/Applications/Orca Computer Use.app')
mockPermissionStatus('{"accessibility":"granted","screenshots":"not-granted"}')
await expect(getComputerUsePermissionStatus()).resolves.toEqual({
platform: 'darwin',
helperAppPath: '/Applications/Orca Computer Use.app',
helperUnavailableReason: null,
permissions: [
{ id: 'accessibility', status: 'granted' },
{ id: 'screenshots', status: 'not-granted' }
]
})
expect(spawn).toHaveBeenCalledWith(
'/usr/bin/open',
[
'-n',
'/Applications/Orca Computer Use.app',
'--args',
'--permission-status-file',
'/tmp/orca-computer-use-permissions-test/status.json'
],
{ stdio: ['ignore', 'pipe', 'pipe'] }
)
expect(spawnSync).not.toHaveBeenCalled()
expect(readFile).toHaveBeenCalledWith(
'/tmp/orca-computer-use-permissions-test/status.json',
'utf8'
)
expect(rm).toHaveBeenCalledWith('/tmp/orca-computer-use-permissions-test', {
recursive: true,
force: true
})
})
it('resets stale macOS TCC grants for the helper bundle id', async () => {
resolveHelperAppPathMock.mockReturnValue('/Applications/Orca Computer Use.app')
vi.mocked(readFile)
@@ -359,11 +228,7 @@ describe('openComputerUsePermissions', () => {
})
expect(execFileSync).toHaveBeenCalledWith(
'/usr/libexec/PlistBuddy',
[
'-c',
'Print :CFBundleIdentifier',
'/Applications/Orca Computer Use.app/Contents/Info.plist'
],
['-c', 'Print :CFBundleIdentifier', helperInfoPlistPath],
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }
)
expect(spawnSync).toHaveBeenCalledWith(
@@ -377,22 +242,6 @@ describe('openComputerUsePermissions', () => {
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
)
})
it('returns unavailable permission status when the helper app is missing on macOS', async () => {
const { getComputerUsePermissionStatus } = await import('./macos-computer-use-permissions')
resolveHelperAppPathMock.mockReturnValue(null)
await expect(getComputerUsePermissionStatus()).resolves.toEqual({
platform: 'darwin',
helperAppPath: null,
helperUnavailableReason: 'Orca Computer Use.app was not found',
permissions: [
{ id: 'accessibility', status: 'not-granted' },
{ id: 'screenshots', status: 'not-granted' }
]
})
expect(execFileSync).not.toHaveBeenCalled()
})
})
function mockPermissionStatus(json: string): void {
@@ -1,25 +1,18 @@
/* oxlint-disable max-lines -- Why: permission setup, status probes, and TCC
reset share the helper-app identity contract and platform guards. */
import { execFileSync, spawn, spawnSync } from 'child_process'
import { mkdtemp, readFile, rm, stat } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import { setTimeout as delay } from 'timers/promises'
import { RuntimeClientError } from './runtime-client-error'
import {
resolveMacOSComputerUseAppPath,
resolveMacOSComputerUseExecutablePath
} from './macos-native-provider-paths'
import { resolveMacOSComputerUseAppPath } from './macos-native-provider-paths'
import { getComputerUsePermissionStatus } from './macos-computer-use-permission-status'
import type {
ComputerUsePermissionId,
ComputerUsePermissionResetResult,
ComputerUsePermissionSetupResult,
ComputerUsePermissionStatus,
ComputerUsePermissionStatusResult
} from '../../shared/computer-use-permissions-types'
const DEFAULT_COMPUTER_USE_BUNDLE_ID = 'com.stablyai.orca.computer-use'
const PERMISSION_STATUS_HELPER_LAUNCH_TIMEOUT_MS = 5_000
export { getComputerUsePermissionStatus } from './macos-computer-use-permission-status'
export function openComputerUsePermissions(
permissionId?: ComputerUsePermissionId
@@ -139,183 +132,6 @@ function closeExistingPermissionHelpers(): void {
}
}
export function getComputerUsePermissionStatus(): Promise<ComputerUsePermissionStatusResult> {
return getComputerUsePermissionStatusAsync()
}
async function getComputerUsePermissionStatusAsync(): Promise<ComputerUsePermissionStatusResult> {
if (process.platform !== 'darwin') {
return {
platform: process.platform,
helperAppPath: null,
helperUnavailableReason: null,
permissions: [
{ id: 'accessibility', status: 'unsupported' },
{ id: 'screenshots', status: 'unsupported' }
]
}
}
const helperAppPath = resolveMacOSComputerUseAppPath()
if (!helperAppPath) {
return createUnavailablePermissionStatus('Orca Computer Use.app was not found', null)
}
const executablePath = resolveMacOSComputerUseExecutablePath()
if (!executablePath) {
return createUnavailablePermissionStatus(
`${helperAppPath}/Contents/MacOS/orca-computer-use-macos was not found`,
helperAppPath
)
}
const raw = await readPermissionStatusFromHelperApp(helperAppPath)
return {
platform: process.platform,
helperAppPath,
helperUnavailableReason: null,
permissions: [
{ id: 'accessibility', status: raw.accessibility ?? 'not-granted' },
{ id: 'screenshots', status: raw.screenshots ?? 'not-granted' }
]
}
}
function createUnavailablePermissionStatus(
reason: string,
helperAppPath: string | null
): ComputerUsePermissionStatusResult {
return {
platform: process.platform,
helperAppPath,
helperUnavailableReason: reason,
permissions: [
{ id: 'accessibility', status: 'not-granted' },
{ id: 'screenshots', status: 'not-granted' }
]
}
}
async function readPermissionStatusFromHelperApp(
helperAppPath: string
): Promise<Partial<Record<ComputerUsePermissionId, ComputerUsePermissionStatus>>> {
const tempDir = await mkdtemp(join(tmpdir(), 'orca-computer-use-permissions-'))
const statusPath = join(tempDir, 'status.json')
try {
// Why: TCC status must be checked through the helper app identity. Directly
// execing the binary can inherit the parent app's already-granted context.
await launchPermissionStatusHelper(helperAppPath, statusPath)
for (let attempt = 0; attempt < 50; attempt++) {
if (await fileExists(statusPath)) {
const output = await readFile(statusPath, 'utf8')
return JSON.parse(output) as Partial<
Record<ComputerUsePermissionId, ComputerUsePermissionStatus>
>
}
await delay(100)
}
throw new RuntimeClientError('accessibility_error', 'Timed out checking permissions')
} finally {
await rm(tempDir, { recursive: true, force: true })
}
}
function launchPermissionStatusHelper(helperAppPath: string, statusPath: string): Promise<void> {
return new Promise((resolve, reject) => {
const launch = spawn(
'/usr/bin/open',
['-n', helperAppPath, '--args', '--permission-status-file', statusPath],
{
stdio: ['ignore', 'pipe', 'pipe']
}
)
let stdout = ''
let stderr = ''
launch.stdout?.setEncoding('utf8')
launch.stderr?.setEncoding('utf8')
const onStdoutData = (chunk: string): void => {
stdout += chunk
}
const onStderrData = (chunk: string): void => {
stderr += chunk
}
let settled = false
let launchTimeout: ReturnType<typeof setTimeout> | null = null
const removeListeners = (): void => {
launch.stdout?.off('data', onStdoutData)
launch.stderr?.off('data', onStderrData)
launch.off('error', onError)
launch.off('close', onClose)
if (launchTimeout) {
clearTimeout(launchTimeout)
launchTimeout = null
}
}
const settleResolve = (): void => {
if (settled) {
return
}
settled = true
removeListeners()
resolve()
}
const settleReject = (error: Error): void => {
if (settled) {
return
}
settled = true
removeListeners()
reject(error)
}
const onError = (): void => {
settleReject(
new RuntimeClientError(
'accessibility_error',
'Could not check permissions: failed to launch helper'
)
)
}
const onClose = (status: number | null): void => {
if (status === 0) {
settleResolve()
return
}
const detail = stderr.trim() || stdout.trim() || `exit ${status ?? 'unknown'}`
settleReject(
new RuntimeClientError('accessibility_error', `Could not check permissions: ${detail}`)
)
}
const onTimeout = (): void => {
launch.kill()
settleReject(
new RuntimeClientError('accessibility_error', 'Timed out launching permission helper')
)
}
// Why: the status-file polling timeout only starts after `open` exits; if
// `open` wedges first, permission checks would otherwise stay pending.
launchTimeout = setTimeout(onTimeout, PERMISSION_STATUS_HELPER_LAUNCH_TIMEOUT_MS)
if (typeof launchTimeout.unref === 'function') {
launchTimeout.unref()
}
launch.stdout?.on('data', onStdoutData)
launch.stderr?.on('data', onStderrData)
launch.on('error', onError)
launch.on('close', onClose)
})
}
async function fileExists(path: string): Promise<boolean> {
try {
await stat(path)
return true
} catch {
return false
}
}
function readComputerUseBundleId(helperAppPath: string): string {
const infoPlistPath = join(helperAppPath, 'Contents', 'Info.plist')
try {
@@ -0,0 +1,10 @@
import { resolveMacOSComputerUseExecutablePath } from './macos-native-provider-paths'
import { isMacOS14OrNewer } from './macos-native-provider-transport'
export function shouldUseMacOSNativeProvider(): boolean {
return (
process.platform === 'darwin' &&
isMacOS14OrNewer() &&
resolveMacOSComputerUseExecutablePath() !== null
)
}
@@ -42,12 +42,13 @@ vi.mock('./macos-native-provider-socket', () => ({
class FakeSocket extends EventEmitter {
destroyed = false
writes: string[] = []
writeError: Error | null = null
setEncoding(): void {}
write(line: string, callback?: (error?: Error | null) => void): boolean {
this.writes.push(line)
callback?.(null)
callback?.(this.writeError)
return true
}
@@ -198,6 +199,149 @@ describe('MacOSNativeProviderClient', () => {
await expect(secondCall).resolves.toEqual(capabilities)
})
it('invalidates the active socket when a helper write fails', async () => {
const { MacOSNativeProviderClient } = await loadClientModule()
const client = new MacOSNativeProviderClient()
const firstCall = client.capabilities()
await vi.waitFor(() => expect(sockets).toHaveLength(1))
const firstSocket = sockets[0]!
const firstSocketDirectory = mkdtempSyncMock.mock.results[0]?.value as string
firstSocket.writeError = new Error('write EPIPE')
await expect(firstCall).rejects.toThrow('write EPIPE')
expect(firstSocket.destroyed).toBe(true)
expect(firstSocket.listenerCount('data')).toBe(0)
expect(firstSocket.listenerCount('close')).toBe(0)
expect(firstSocket.listenerCount('error')).toBe(1)
expect(rmSyncMock).toHaveBeenCalledWith(firstSocketDirectory, {
recursive: true,
force: true
})
const secondCall = client.capabilities()
await vi.waitFor(() => expect(sockets).toHaveLength(2))
const secondSocket = sockets[1]!
await vi.waitFor(() => expect(secondSocket.writes).toHaveLength(1))
const secondRequest = JSON.parse(secondSocket.writes[0]!) as { id: number }
secondSocket.emit(
'data',
`${JSON.stringify({
id: secondRequest.id,
ok: true,
result: { protocolVersion: 1, supports: {} }
})}\n`
)
await expect(secondCall).resolves.toMatchObject({ protocolVersion: 1 })
})
it('rejects actions that the native provider does not advertise', async () => {
const { MacOSNativeProviderClient } = await loadClientModule()
const client = new MacOSNativeProviderClient()
const call = client.action('setValue', {
app: 'TextEdit',
elementIndex: 0,
value: 'draft'
})
await vi.waitFor(() => expect(sockets).toHaveLength(1))
const socket = sockets[0]!
await vi.waitFor(() => expect(socket.writes).toHaveLength(1))
const handshakeRequest = JSON.parse(socket.writes[0]!) as { id: number }
socket.emit(
'data',
`${JSON.stringify({
id: handshakeRequest.id,
ok: true,
result: macOSProviderCapabilities({ setValue: false })
})}\n`
)
await expect(call).rejects.toMatchObject({
code: 'unsupported_capability',
message: expect.stringContaining('actions.setValue')
})
expect(socket.writes).toHaveLength(1)
})
it('rejects malformed action payloads before starting the native helper', async () => {
const { MacOSNativeProviderClient } = await loadClientModule()
const client = new MacOSNativeProviderClient()
await expect(client.action('click', { elementIndex: 0 })).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Missing app')
})
await expect(client.action('click', { app: 'TextEdit' })).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Click requires')
})
await expect(client.action('typeText', { app: 'TextEdit', text: '' })).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Missing text')
})
await expect(
client.action('pressKey', { app: 'TextEdit', key: 'CmdOrCtrl+V' })
).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Press-key accepts one key only')
})
await expect(client.action('hotkey', { app: 'TextEdit', key: 'A' })).rejects.toMatchObject({
code: 'invalid_argument',
message: expect.stringContaining('Hotkey requires')
})
expect(providers).toHaveLength(0)
expect(sockets).toHaveLength(0)
expect(spawnMock).not.toHaveBeenCalled()
expect(connectMacOSProviderSocketMock).not.toHaveBeenCalled()
})
it('normalizes unverified synthetic native action results', async () => {
const { MacOSNativeProviderClient } = await loadClientModule()
const client = new MacOSNativeProviderClient()
const call = client.action('click', {
app: 'TextEdit',
elementIndex: 0
})
await vi.waitFor(() => expect(sockets).toHaveLength(1))
const socket = sockets[0]!
await vi.waitFor(() => expect(socket.writes).toHaveLength(1))
const handshakeRequest = JSON.parse(socket.writes[0]!) as { id: number }
socket.emit(
'data',
`${JSON.stringify({
id: handshakeRequest.id,
ok: true,
result: macOSProviderCapabilities()
})}\n`
)
await vi.waitFor(() => expect(socket.writes).toHaveLength(2))
const actionRequest = JSON.parse(socket.writes[1]!) as { id: number }
socket.emit(
'data',
`${JSON.stringify({
id: actionRequest.id,
ok: true,
result: {
snapshot: {},
action: { path: 'synthetic', actionName: null, fallbackReason: null }
}
})}\n`
)
await expect(call).resolves.toMatchObject({
action: {
path: 'synthetic',
verification: { state: 'unverified', reason: 'synthetic_input' }
}
})
})
it('removes the parent-owned token file after the helper socket connects', async () => {
const { MacOSNativeProviderClient } = await loadClientModule()
const client = new MacOSNativeProviderClient()
@@ -326,3 +470,41 @@ describe('MacOSNativeProviderClient', () => {
expect(providers[0]!.kill).toHaveBeenCalledWith('SIGTERM')
})
})
function macOSProviderCapabilities(actions: Partial<Record<string, boolean>> = {}) {
return {
platform: 'darwin',
provider: 'orca-computer-use-macos',
providerVersion: '1.0.0',
protocolVersion: 1,
supports: {
apps: { list: true, bundleIds: true, pids: true },
windows: {
list: true,
targetById: true,
targetByIndex: true,
focus: false,
moveResize: false
},
observation: {
screenshot: true,
annotatedScreenshot: false,
elementFrames: true,
ocr: false
},
actions: {
click: true,
typeText: true,
pressKey: true,
hotkey: true,
pasteText: true,
scroll: true,
drag: true,
setValue: true,
performAction: true,
...actions
},
surfaces: { menus: false, dialogs: false, dock: false, menubar: false }
}
}
}
+63 -158
View File
@@ -1,10 +1,5 @@
/* eslint-disable max-lines -- Why: the macOS provider transport owns one lifecycle across stdio fallback and helper-app socket mode. */
import { spawn, type ChildProcess } from 'child_process'
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { rmSync } from 'fs'
import type net from 'net'
import { release, tmpdir } from 'os'
import { join } from 'path'
import { randomUUID } from 'crypto'
import type {
ComputerActionResult,
ComputerListAppsResult,
@@ -14,6 +9,7 @@ import type {
} from '../../shared/runtime-types'
import {
assertMacOSProviderCapability,
macOSActionCapabilityKey,
REQUIRED_MACOS_PROVIDER_PROTOCOL_VERSION,
type NativeActionMethod,
type NativeMethod,
@@ -22,23 +18,16 @@ import {
writeNativeProviderLine
} from './macos-native-provider-contract'
import { resolveMacOSComputerUseExecutablePath } from './macos-native-provider-paths'
import { connectMacOSProviderSocket } from './macos-native-provider-socket'
import {
attachMacOSNativeProviderSocketListeners,
consumeNativeProviderLines,
startMacOSNativeProviderSocket
} from './macos-native-provider-transport'
import { validateComputerProviderActionParams } from './computer-provider-action-validation'
import { normalizeComputerActionResult } from './computer-action-verification-normalization'
import { RuntimeClientError } from './runtime-client-error'
const REQUEST_TIMEOUT_MS = 60_000
const HELPER_CONNECT_TIMEOUT_MS = 10_000
// Why: Node treats unhandled socket 'error' events as process exceptions, so
// stale helper sockets keep a no-op listener that does not retain the client.
function ignoreStaleSocketError(): void {}
export function shouldUseMacOSNativeProvider(): boolean {
return (
process.platform === 'darwin' &&
isMacOS14OrNewer() &&
resolveMacOSComputerUseExecutablePath() !== null
)
}
export class MacOSNativeProviderClient {
private socket: net.Socket | null = null
@@ -67,7 +56,12 @@ export class MacOSNativeProviderClient {
return (await this.call('getAppState', params)) as ComputerSnapshotResult
}
async action(method: NativeActionMethod, params: unknown): Promise<ComputerActionResult> {
return (await this.call(method, params)) as ComputerActionResult
validateComputerProviderActionParams(
method,
params && typeof params === 'object' ? (params as Record<string, unknown>) : {}
)
await this.ensureActionSupported(method)
return normalizeComputerActionResult((await this.call(method, params)) as ComputerActionResult)
}
shutdown(): void {
const socket = this.socket
@@ -121,15 +115,17 @@ export class MacOSNativeProviderClient {
try {
await writeNativeProviderLine(transport, line)
} catch (error) {
const wrapped = new RuntimeClientError(
'accessibility_error',
error instanceof Error ? error.message : String(error)
)
const pending = this.pending.get(id)
if (pending) {
clearTimeout(pending.timer)
this.pending.delete(id)
}
throw new RuntimeClientError(
'accessibility_error',
error instanceof Error ? error.message : String(error)
)
this.invalidateActiveSocketAfterWriteFailure(transport, wrapped)
throw wrapped
}
return await result
}
@@ -168,6 +164,9 @@ export class MacOSNativeProviderClient {
`native macOS provider does not support ${String(group)}.${capability}`
)
}
private async ensureActionSupported(method: NativeActionMethod): Promise<void> {
await this.ensureCapability('actions', macOSActionCapabilityKey(method))
}
private async ensureSocketStarted(helperExecutablePath: string): Promise<net.Socket> {
if (this.socket && !this.socket.destroyed) {
return this.socket
@@ -189,68 +188,25 @@ export class MacOSNativeProviderClient {
}
private async startSocket(helperExecutablePath: string): Promise<net.Socket> {
const startGeneration = ++this.socketStartGeneration
const socketDirectory = mkdtempSync(join(tmpdir(), 'orca-computer-use-'))
chmodSync(socketDirectory, 0o700)
const socketPath = join(socketDirectory, 'provider.sock')
const socketToken = randomUUID()
const socketTokenPath = join(socketDirectory, 'provider.token')
this.socketDirectory = socketDirectory
this.socketPath = socketPath
this.socketToken = socketToken
writeFileSync(socketTokenPath, socketToken, { encoding: 'utf8', mode: 0o600 })
// Why: launching the nested helper via LaunchServices can make TCC evaluate
// Orca.app as responsible; the signed helper executable owns this grant.
const provider = spawnProvider(helperExecutablePath, socketPath, socketTokenPath)
const providerFailure = waitForProviderLaunchFailure(provider)
const connectAbort = new AbortController()
try {
const socket = await Promise.race([
connectMacOSProviderSocket(socketPath, HELPER_CONNECT_TIMEOUT_MS, connectAbort.signal),
providerFailure.promise
])
providerFailure.cleanup()
rmSync(socketTokenPath, { force: true })
// Why: shutdown/retry can supersede an in-flight connect; old starts
// must not adopt replacement state or clean up the replacement helper.
if (this.socketStartGeneration !== startGeneration || this.socketPath !== socketPath) {
socket.destroy()
throw new RuntimeClientError(
'accessibility_error',
'native macOS provider startup was superseded'
)
}
socket.setEncoding('utf8')
this.socketBuffer = ''
const onData = (chunk: string) => this.handleSocketData(socket, chunk)
const onClose = () => this.handleSocketClose(socket)
const onError = (error: Error) => this.handleTransportError(socket, error)
socket.on('data', onData)
socket.on('close', onClose)
socket.on('error', onError)
this.socketListenerCleanup = () => {
socket.off('data', onData)
socket.off('close', onClose)
socket.off('error', onError)
socket.off('error', ignoreStaleSocketError)
socket.on('error', ignoreStaleSocketError)
}
this.socket = socket
return socket
} catch (error) {
connectAbort.abort()
providerFailure.cleanup()
// Why: connect failures happen after spawn; terminate the detached
// helper so repeated startup attempts do not leave orphan providers.
provider.kill('SIGTERM')
if (
const started = await startMacOSNativeProviderSocket({
helperExecutablePath,
isCurrent: (socketPath) =>
this.socketStartGeneration === startGeneration &&
this.socketDirectory === socketDirectory
) {
this.cleanupSocketDirectory()
this.socketToken = null
}
throw error
}
(this.socketPath === null || this.socketPath === socketPath)
})
this.socketDirectory = started.socketDirectory
this.socketPath = started.socketPath
this.socketToken = started.socketToken
const socket = started.socket
socket.setEncoding('utf8')
this.socketBuffer = ''
this.socketListenerCleanup = attachMacOSNativeProviderSocketListeners(socket, {
data: (chunk) => this.handleSocketData(socket, chunk),
close: () => this.handleSocketClose(socket),
error: (error) => this.handleTransportError(socket, error)
})
this.socket = socket
return socket
}
private handleSocketData(socket: net.Socket, chunk: string): void {
// Why: a timed-out helper socket can emit after a replacement starts.
@@ -259,21 +215,9 @@ export class MacOSNativeProviderClient {
return
}
this.socketBuffer += chunk
this.socketBuffer = this.consumeLines(this.socketBuffer)
}
private consumeLines(buffer: string): string {
let remaining = buffer
while (true) {
const newline = remaining.indexOf('\n')
if (newline < 0) {
return remaining
}
const line = remaining.slice(0, newline)
remaining = remaining.slice(newline + 1)
if (line.trim()) {
this.handleLine(line)
}
}
this.socketBuffer = consumeNativeProviderLines(this.socketBuffer, (line) =>
this.handleLine(line)
)
}
private handleLine(line: string): void {
let response: NativeResponse
@@ -295,8 +239,7 @@ export class MacOSNativeProviderClient {
pending.reject(new RuntimeClientError(response.error.code, response.error.message))
}
private handleSocketClose(socket: net.Socket): void {
// Why: late close from a prior helper socket must not tear down the active
// replacement socket or reject its in-flight requests.
// Why: late close from a prior helper socket must not tear down the active replacement.
if (this.socket !== socket) {
return
}
@@ -314,8 +257,7 @@ export class MacOSNativeProviderClient {
return
}
this.cleanupActiveSocketListeners()
// Why: an active transport error makes the helper socket unreliable; the
// next request must reconnect instead of reusing a broken socket.
// Why: an active transport error makes the helper socket unreliable for the next request.
this.socket = null
this.socketBuffer = ''
if (!socket.destroyed) {
@@ -324,6 +266,22 @@ export class MacOSNativeProviderClient {
this.cleanupSocketDirectory()
this.rejectPending(new RuntimeClientError('accessibility_error', error.message))
}
private invalidateActiveSocketAfterWriteFailure(
socket: net.Socket,
error: RuntimeClientError
): void {
if (this.socket !== socket) {
return
}
this.cleanupActiveSocketListeners()
this.socket = null
this.socketBuffer = ''
if (!socket.destroyed) {
socket.destroy()
}
this.cleanupSocketDirectory()
this.rejectPending(error)
}
private cleanupSocketDirectory(): void {
if (!this.socketDirectory) {
return
@@ -345,56 +303,3 @@ export class MacOSNativeProviderClient {
cleanup?.()
}
}
function isMacOS14OrNewer(): boolean {
const darwinMajor = Number.parseInt(release().split('.')[0] ?? '', 10)
return Number.isFinite(darwinMajor) && darwinMajor >= 23
}
function spawnProvider(
helperExecutablePath: string,
socketPath: string,
socketTokenPath: string
): ChildProcess {
const provider = spawn(
helperExecutablePath,
['--agent', socketPath, '--token-file', socketTokenPath],
{ detached: true, stdio: 'ignore' }
)
provider.unref()
return provider
}
function waitForProviderLaunchFailure(provider: ChildProcess): {
promise: Promise<never>
cleanup: () => void
} {
let cleanup = (): void => {}
const promise = new Promise<never>((_resolve, reject) => {
const fail = (error: Error) => {
reject(
new RuntimeClientError(
'accessibility_error',
`native macOS helper app failed to start: ${error.message}`
)
)
}
const exit = (code: number | null, signal: NodeJS.Signals | null) => {
reject(
new RuntimeClientError(
'accessibility_error',
`native macOS helper app exited before connecting: ${
typeof code === 'number' ? `code ${code}` : `signal ${signal ?? 'unknown'}`
}`
)
)
}
provider.once('error', fail)
provider.once('exit', exit)
cleanup = () => {
provider.off('error', fail)
provider.off('exit', exit)
}
})
return { promise, cleanup }
}
@@ -43,6 +43,23 @@ export function assertMacOSProviderCapability(
return groupCapabilities?.[capability] === true
}
export function macOSActionCapabilityKey(
method: NativeActionMethod
): keyof ComputerProviderCapabilities['supports']['actions'] {
const keys = {
click: 'click',
performSecondaryAction: 'performAction',
scroll: 'scroll',
drag: 'drag',
typeText: 'typeText',
pressKey: 'pressKey',
hotkey: 'hotkey',
pasteText: 'pasteText',
setValue: 'setValue'
} satisfies Record<NativeActionMethod, keyof ComputerProviderCapabilities['supports']['actions']>
return keys[method]
}
export function writeNativeProviderLine(transport: net.Socket, line: string): Promise<void> {
return new Promise((resolve, reject) => {
transport.write(line, (error) => {
@@ -0,0 +1,163 @@
import { spawn, type ChildProcess } from 'child_process'
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import type net from 'net'
import { release, tmpdir } from 'os'
import { join } from 'path'
import { randomUUID } from 'crypto'
import { connectMacOSProviderSocket } from './macos-native-provider-socket'
import { RuntimeClientError } from './runtime-client-error'
const HELPER_CONNECT_TIMEOUT_MS = 10_000
export type StartedMacOSProviderSocket = {
socket: net.Socket
socketDirectory: string
socketPath: string
socketToken: string
}
export function isMacOS14OrNewer(): boolean {
const darwinMajor = Number.parseInt(release().split('.')[0] ?? '', 10)
return Number.isFinite(darwinMajor) && darwinMajor >= 23
}
// Why: Node treats unhandled socket 'error' events as process exceptions, so
// stale helper sockets keep a no-op listener that does not retain the client.
export function ignoreStaleSocketError(): void {}
export function attachMacOSNativeProviderSocketListeners(
socket: net.Socket,
listeners: {
data: (chunk: string) => void
close: () => void
error: (error: Error) => void
}
): () => void {
socket.on('data', listeners.data)
socket.on('close', listeners.close)
socket.on('error', listeners.error)
return () => {
socket.off('data', listeners.data)
socket.off('close', listeners.close)
socket.off('error', listeners.error)
socket.off('error', ignoreStaleSocketError)
socket.on('error', ignoreStaleSocketError)
}
}
export function consumeNativeProviderLines(
buffer: string,
handleLine: (line: string) => void
): string {
let remaining = buffer
while (true) {
const newline = remaining.indexOf('\n')
if (newline < 0) {
return remaining
}
const line = remaining.slice(0, newline)
remaining = remaining.slice(newline + 1)
if (line.trim()) {
handleLine(line)
}
}
}
export async function startMacOSNativeProviderSocket({
helperExecutablePath,
isCurrent
}: {
helperExecutablePath: string
isCurrent: (socketPath: string) => boolean
}): Promise<StartedMacOSProviderSocket> {
const socketDirectory = mkdtempSync(join(tmpdir(), 'orca-computer-use-'))
chmodSync(socketDirectory, 0o700)
const socketPath = join(socketDirectory, 'provider.sock')
const socketToken = randomUUID()
const socketTokenPath = join(socketDirectory, 'provider.token')
writeFileSync(socketTokenPath, socketToken, { encoding: 'utf8', mode: 0o600 })
// Why: launching the nested helper via LaunchServices can make TCC evaluate
// Orca.app as responsible; the signed helper executable owns this grant.
const provider = spawnProvider(helperExecutablePath, socketPath, socketTokenPath)
const providerFailure = waitForProviderLaunchFailure(provider)
const connectAbort = new AbortController()
try {
const socket = await Promise.race([
connectMacOSProviderSocket(socketPath, HELPER_CONNECT_TIMEOUT_MS, connectAbort.signal),
providerFailure.promise
])
providerFailure.cleanup()
rmSync(socketTokenPath, { force: true })
if (!isCurrent(socketPath)) {
socket.destroy()
cleanupSocketDirectory(socketDirectory)
throw new RuntimeClientError(
'accessibility_error',
'native macOS provider startup was superseded'
)
}
return { socket, socketDirectory, socketPath, socketToken }
} catch (error) {
connectAbort.abort()
providerFailure.cleanup()
// Why: connect failures happen after spawn; terminate the detached helper
// so repeated startup attempts do not leave orphan providers.
provider.kill('SIGTERM')
if (isCurrent(socketPath)) {
cleanupSocketDirectory(socketDirectory)
}
throw error
}
}
function cleanupSocketDirectory(socketDirectory: string): void {
rmSync(socketDirectory, { recursive: true, force: true })
}
function spawnProvider(
helperExecutablePath: string,
socketPath: string,
socketTokenPath: string
): ChildProcess {
const provider = spawn(
helperExecutablePath,
['--agent', socketPath, '--token-file', socketTokenPath],
{ detached: true, stdio: 'ignore' }
)
provider.unref()
return provider
}
function waitForProviderLaunchFailure(provider: ChildProcess): {
promise: Promise<never>
cleanup: () => void
} {
let cleanup = (): void => {}
const promise = new Promise<never>((_resolve, reject) => {
const fail = (error: Error) => {
reject(
new RuntimeClientError(
'accessibility_error',
`native macOS helper app failed to start: ${error.message}`
)
)
}
const exit = (code: number | null, signal: NodeJS.Signals | null) => {
reject(
new RuntimeClientError(
'accessibility_error',
`native macOS helper app exited before connecting: ${
typeof code === 'number' ? `code ${code}` : `signal ${signal ?? 'unknown'}`
}`
)
)
}
provider.once('error', fail)
provider.once('exit', exit)
cleanup = () => {
provider.off('error', fail)
provider.off('exit', exit)
}
})
return { promise, cleanup }
}
+210 -6
View File
@@ -1,6 +1,10 @@
import { EventEmitter } from 'events'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { callComputerSidecarCapabilities, resetComputerSidecarForTest } from './sidecar-client'
import {
callComputerSidecarAction,
callComputerSidecarCapabilities,
resetComputerSidecarForTest
} from './sidecar-client'
const { forkMock } = vi.hoisted(() => ({
forkMock: vi.fn()
@@ -19,27 +23,42 @@ type SentRequest = {
class FakeChildProcess extends EventEmitter {
killed = false
sent: SentRequest[] = []
deferSendCallback = false
sendCallbacks: ((error: Error | null) => void)[] = []
send(message: SentRequest, callback?: (error: Error | null) => void): boolean {
this.sent.push(message)
callback?.(null)
return true
}
send: ((message: SentRequest, callback?: (error: Error | null) => void) => boolean) | undefined =
(message, callback) => {
this.sent.push(message)
if (callback && this.deferSendCallback) {
this.sendCallbacks.push(callback)
} else {
callback?.(null)
}
return true
}
kill(): boolean {
this.killed = true
return true
}
flushSendCallback(error: Error | null): void {
this.sendCallbacks.shift()?.(error)
}
}
describe('computer sidecar client', () => {
const children: FakeChildProcess[] = []
let deferNextSendCallback = false
beforeEach(() => {
vi.useFakeTimers()
children.length = 0
deferNextSendCallback = false
forkMock.mockImplementation(() => {
const child = new FakeChildProcess()
child.deferSendCallback = deferNextSendCallback
deferNextSendCallback = false
children.push(child)
return child
})
@@ -114,4 +133,189 @@ describe('computer sidecar client', () => {
await expect(secondCall).resolves.toEqual({ supports: { screenshots: true } })
})
it('serializes requests so desktop actions cannot overlap', async () => {
const firstCall = callComputerSidecarCapabilities()
const secondCall = callComputerSidecarCapabilities()
const child = children[0]!
expect(child.sent).toHaveLength(1)
const firstRequest = child.sent[0]!
child.emit('message', {
id: firstRequest.id,
ok: true,
result: { provider: 'first' }
})
await expect(firstCall).resolves.toEqual({ provider: 'first' })
await vi.waitFor(() => expect(child.sent).toHaveLength(2))
const secondRequest = child.sent[1]!
child.emit('message', {
id: secondRequest.id,
ok: true,
result: { provider: 'second' }
})
await expect(secondCall).resolves.toEqual({ provider: 'second' })
})
it('marks synthetic action results without provider verification as unverified', async () => {
const call = callComputerSidecarAction('click', { app: 'Finder', elementIndex: 0 })
const child = children[0]!
const request = child.sent[0]!
child.emit('message', {
id: request.id,
ok: true,
result: {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', id: 1, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 1,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'synthetic',
actionName: null,
fallbackReason: null,
targetWindowId: 1
}
}
})
await expect(call).resolves.toMatchObject({
action: {
path: 'synthetic',
verification: { state: 'unverified', reason: 'synthetic_input' }
}
})
})
it('marks clipboard action results without provider verification as unverified', async () => {
const call = callComputerSidecarAction('pasteText', { app: 'Finder', text: 'draft' })
const child = children[0]!
const request = child.sent[0]!
child.emit('message', {
id: request.id,
ok: true,
result: {
snapshot: {
id: 'snap-1',
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
window: { title: 'Finder', id: 1, width: 800, height: 600 },
coordinateSpace: 'window',
treeText: 'tree',
elementCount: 1,
focusedElementId: null
},
screenshot: null,
screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' },
action: {
path: 'clipboard',
actionName: 'paste',
fallbackReason: null,
targetWindowId: 1
}
}
})
await expect(call).resolves.toMatchObject({
action: {
path: 'clipboard',
verification: { state: 'unverified', reason: 'clipboard_paste' }
}
})
})
it('rejects queued requests after the active request times out', async () => {
const firstCall = callComputerSidecarCapabilities()
const secondCall = callComputerSidecarCapabilities()
const firstRejection = expect(firstCall).rejects.toThrow(
'computer sidecar capabilities timed out'
)
const secondRejection = expect(secondCall).rejects.toThrow(
'computer sidecar queue was invalidated'
)
const child = children[0]!
expect(child.sent).toHaveLength(1)
await vi.advanceTimersByTimeAsync(60_000)
await firstRejection
await secondRejection
expect(children).toHaveLength(1)
})
it('rejects queued requests after the active child errors', async () => {
const firstCall = callComputerSidecarCapabilities()
const secondCall = callComputerSidecarCapabilities()
const firstRejection = expect(firstCall).rejects.toThrow('active sidecar failed')
const secondRejection = expect(secondCall).rejects.toThrow(
'computer sidecar queue was invalidated'
)
const child = children[0]!
child.emit('error', new Error('active sidecar failed'))
await firstRejection
await secondRejection
expect(children).toHaveLength(1)
})
it('invalidates queued requests after IPC send fails', async () => {
deferNextSendCallback = true
const firstCall = callComputerSidecarCapabilities()
const secondCall = callComputerSidecarCapabilities()
const firstChild = children[0]!
const firstRejection = expect(firstCall).rejects.toThrow('ipc channel closed')
const secondRejection = expect(secondCall).rejects.toThrow(
'computer sidecar queue was invalidated'
)
firstChild.flushSendCallback(new Error('ipc channel closed'))
await firstRejection
await secondRejection
expect(firstChild.killed).toBe(true)
expect(firstChild.listenerCount('message')).toBe(0)
expect(firstChild.listenerCount('exit')).toBe(0)
expect(firstChild.listenerCount('error')).toBe(1)
const thirdCall = callComputerSidecarCapabilities()
const secondChild = children[1]!
const thirdRequest = secondChild.sent[0]!
secondChild.emit('message', {
id: thirdRequest.id,
ok: true,
result: { supports: { screenshots: true } }
})
await expect(thirdCall).resolves.toEqual({ supports: { screenshots: true } })
})
it('fails immediately when the forked sidecar has no IPC send channel', async () => {
forkMock.mockImplementationOnce(() => {
const child = new FakeChildProcess()
child.send = undefined
children.push(child)
return child
})
const call = callComputerSidecarCapabilities()
await expect(call).rejects.toThrow('computer sidecar IPC is unavailable')
expect(children[0]!.killed).toBe(true)
expect(children[0]!.listenerCount('message')).toBe(0)
expect(children[0]!.listenerCount('exit')).toBe(0)
expect(children[0]!.listenerCount('error')).toBe(1)
})
})
+55 -5
View File
@@ -7,6 +7,7 @@ import type {
ComputerProviderCapabilities,
ComputerSnapshotResult
} from '../../shared/runtime-types'
import { normalizeComputerActionResult } from './computer-action-verification-normalization'
import { RuntimeClientError } from './runtime-client-error'
type ComputerSidecarMethod =
@@ -84,7 +85,9 @@ export async function callComputerSidecarAction(
>,
params: unknown
): Promise<ComputerActionResult> {
return (await getComputerSidecar().call(method, params)) as ComputerActionResult
return normalizeComputerActionResult(
(await getComputerSidecar().call(method, params)) as ComputerActionResult
)
}
export function resetComputerSidecarForTest(): void {
@@ -122,11 +125,46 @@ class ComputerSidecarProcess {
private childListenerCleanup: (() => void) | null = null
private nextId = 1
private pending = new Map<number, PendingRequest>()
private queueTail: Promise<void> | null = null
private queueGeneration = 0
constructor(private readonly entryPath: string) {}
call(method: ComputerSidecarMethod, params: unknown): Promise<unknown> {
const generation = this.queueGeneration
const run = () => {
if (generation !== this.queueGeneration) {
throw new RuntimeClientError(
'accessibility_error',
'computer sidecar queue was invalidated; retry the computer-use request'
)
}
return this.send(method, params)
}
const result = this.queueTail ? this.queueTail.then(run, run) : run()
const tail = result.then(
() => undefined,
() => undefined
)
this.queueTail = tail
void tail.finally(() => {
if (this.queueTail === tail) {
this.queueTail = null
}
})
return result
}
private send(method: ComputerSidecarMethod, params: unknown): Promise<unknown> {
const child = this.ensureStarted()
if (!child.send) {
const error = new RuntimeClientError(
'accessibility_error',
'computer sidecar IPC is unavailable'
)
this.failActiveChild(child, error)
return Promise.reject(error)
}
const id = this.nextId++
const request: ComputerSidecarRequest = { id, method, params }
@@ -138,13 +176,18 @@ class ComputerSidecarProcess {
}, REQUEST_TIMEOUT_MS)
this.pending.set(id, { resolve, reject, timer })
child.send?.(request, (error) => {
child.send(request, (error) => {
if (!error) {
return
}
const wrapped = new RuntimeClientError('accessibility_error', error.message)
if (this.child === child) {
this.failActiveChild(child, wrapped)
return
}
clearTimeout(timer)
this.pending.delete(id)
reject(new RuntimeClientError('accessibility_error', error.message))
reject(wrapped)
})
})
}
@@ -152,6 +195,7 @@ class ComputerSidecarProcess {
shutdown(): void {
const child = this.child
this.child = null
this.queueGeneration++
this.cleanupActiveChildListeners()
for (const [id, pending] of this.pending) {
clearTimeout(pending.timer)
@@ -230,6 +274,7 @@ class ComputerSidecarProcess {
}
this.cleanupActiveChildListeners()
this.child = null
this.queueGeneration++
const detail = signal ? `signal ${signal}` : `code ${code ?? 'unknown'}`
const error = new RuntimeClientError(
'accessibility_error',
@@ -250,12 +295,17 @@ class ComputerSidecarProcess {
this.cleanupActiveChildListeners()
// Why: an active process error makes the IPC sidecar unreliable; restart
// on the next call instead of reusing a broken helper.
this.failActiveChild(child, new RuntimeClientError('accessibility_error', error.message))
}
private failActiveChild(child: ChildProcess, error: RuntimeClientError): void {
this.cleanupActiveChildListeners()
this.child = null
this.queueGeneration++
child.kill('SIGTERM')
const wrapped = new RuntimeClientError('accessibility_error', error.message)
for (const [id, pending] of this.pending) {
clearTimeout(pending.timer)
pending.reject(wrapped)
pending.reject(error)
this.pending.delete(id)
}
}
+5 -17
View File
@@ -1,12 +1,5 @@
/* eslint-disable max-lines -- Why: sidecar dispatch keeps one method table shared across native providers. */
import {
MacOSNativeProviderClient,
shouldUseMacOSNativeProvider
} from './macos-native-provider-client'
import {
DesktopScriptProviderClient,
shouldUseDesktopScriptProvider
} from './desktop-script-provider-client'
import { computerProviderUnavailableMessage } from './computer-provider-unavailable-message'
import { currentComputerProvider, shutdownComputerProviders } from './computer-provider-lifecycle'
import { RuntimeClientError } from './runtime-client-error'
type SidecarRequest = {
@@ -15,11 +8,6 @@ type SidecarRequest = {
params?: Record<string, unknown>
}
const nativeMacOSProvider = shouldUseMacOSNativeProvider() ? new MacOSNativeProviderClient() : null
const desktopScriptProvider = shouldUseDesktopScriptProvider()
? new DesktopScriptProviderClient()
: null
process.once('disconnect', shutdownProviders)
process.once('SIGTERM', () => {
shutdownProviders()
@@ -50,11 +38,11 @@ async function handleMessage(message: unknown): Promise<void> {
}
async function dispatch(method: string, params: Record<string, unknown>): Promise<unknown> {
const provider = nativeMacOSProvider ?? desktopScriptProvider
const provider = currentComputerProvider()
if (!provider) {
throw new RuntimeClientError(
'unsupported_capability',
`computer-use has no native provider for ${process.platform}`
computerProviderUnavailableMessage(process.platform)
)
}
@@ -133,5 +121,5 @@ function errorToResponse(error: unknown): { code: string; message: string } {
}
function shutdownProviders(): void {
nativeMacOSProvider?.shutdown()
shutdownComputerProviders()
}
@@ -0,0 +1,84 @@
import { describe, expect, it } from 'vitest'
import { z } from 'zod'
import { RpcDispatcher } from './dispatcher'
import { defineMethod, type RpcRequest } from './core'
import type { OrcaRuntimeService } from '../orca-runtime'
function makeRequest(method: string, params?: unknown): RpcRequest {
return { id: 'req-1', authToken: 'tok', method, params }
}
function makeRuntime(): OrcaRuntimeService {
return {
getRuntimeId: () => 'test-runtime'
} as OrcaRuntimeService
}
const METHODS = [
defineMethod({
name: 'computer.click',
params: z.object({ app: z.string().min(1, 'Missing app') }),
handler: () => ({ ok: true })
}),
defineMethod({
name: 'browser.click',
params: z.object({ page: z.string().min(1, 'Missing page') }),
handler: () => ({ ok: true })
})
]
describe('RpcDispatcher computer-use validation errors', () => {
it('adds recovery steps to one-shot computer schema failures', async () => {
const dispatcher = new RpcDispatcher({ runtime: makeRuntime(), methods: METHODS })
const response = await dispatcher.dispatch(makeRequest('computer.click', {}))
expect(response).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: expect.stringContaining('expected string'),
data: {
nextSteps: expect.arrayContaining([
expect.stringContaining('Fix the command flags or RPC params'),
expect.stringContaining('Do not retry')
])
}
}
})
})
it('adds recovery steps to streaming-transport computer schema failures', async () => {
const messages: string[] = []
const dispatcher = new RpcDispatcher({ runtime: makeRuntime(), methods: METHODS })
await dispatcher.dispatchStreaming(makeRequest('computer.click', {}), (message) =>
messages.push(message)
)
expect(JSON.parse(messages[0]!)).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
data: {
nextSteps: expect.arrayContaining([expect.stringContaining('Do not retry')])
}
}
})
})
it('does not add computer-use recovery steps to unrelated schema failures', async () => {
const dispatcher = new RpcDispatcher({ runtime: makeRuntime(), methods: METHODS })
const response = await dispatcher.dispatch(makeRequest('browser.click', {}))
expect(response).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: expect.stringContaining('expected string')
}
})
expect(response.ok === false ? response.error : null).not.toHaveProperty('data')
})
})
+23 -3
View File
@@ -16,7 +16,13 @@ import {
import type { TerminalStreamFrame } from '../../../shared/terminal-stream-protocol'
import type { FeatureInteractionId } from '../../../shared/feature-interactions'
import { isBrowserPaneUiRuntimeRpcParams } from '../../../shared/runtime-rpc-feature-interaction-source'
import { errorResponse, mapBrowserError, mapRuntimeError, successResponse } from './errors'
import {
computerErrorData,
errorResponse,
mapBrowserError,
mapRuntimeError,
successResponse
} from './errors'
import { ALL_RPC_METHODS } from './methods'
import type { OrcaRuntimeService } from '../orca-runtime'
@@ -176,7 +182,7 @@ export class RpcDispatcher {
const result = method.params.safeParse(rawParams)
if (!result.success) {
return {
error: errorResponse(request.id, meta, 'invalid_argument', formatZodError(result.error))
error: this.invalidArgumentResponse(request, meta, formatZodError(result.error))
}
}
return { value: result.data }
@@ -191,11 +197,25 @@ export class RpcDispatcher {
return mapBrowserError(request.id, meta, error)
}
if (error instanceof ZodError) {
return errorResponse(request.id, meta, 'invalid_argument', formatZodError(error))
return this.invalidArgumentResponse(request, meta, formatZodError(error))
}
return mapRuntimeError(request.id, meta, error)
}
private invalidArgumentResponse(
request: RpcRequest,
meta: RpcEnvelopeMeta,
message: string
): RpcResponse {
return errorResponse(
request.id,
meta,
'invalid_argument',
message,
request.method.startsWith('computer.') ? computerErrorData('invalid_argument') : undefined
)
}
private meta(): RpcEnvelopeMeta {
return { runtimeId: this.runtime.getRuntimeId() }
}
+95
View File
@@ -9,6 +9,101 @@ class LineageError extends Error {
}
describe('mapRuntimeError', () => {
it.each([
['window_not_focused', 'keyboard input requires focus', 'restore-window'],
['permission_denied', 'missing DBUS_SESSION_BUS_ADDRESS', 'permissions'],
['element_not_found', 'fresh element index required', 'get-app-state'],
['unsupported_capability', 'hotkey combinations require xdotool', 'capabilities'],
[
'action_not_supported',
'Raise is not a valid secondary action',
'advertised secondary actions'
],
['value_not_settable', 'element value is not settable', 'settable text element'],
['element_not_clickable', 'element has no actionable frame', 'actionable frame'],
['invalid_argument', 'click_count must be a positive integer', 'Do not retry'],
['action_timeout', 'computer sidecar click timed out', 'do not repeat'],
['screenshot_failed', 'screenshot capture returned no image', '--no-screenshot'],
['accessibility_error', 'desktop script provider is not available', 'capabilities']
])('adds recovery steps for computer-use %s errors', (code, message, recoveryFragment) => {
const error = new Error(message)
Object.assign(error, { code })
const response = mapRuntimeError('req_1', { runtimeId: 'runtime-1' }, error)
expect(response.error).toMatchObject({
code,
message,
data: {
nextSteps: expect.arrayContaining([expect.stringContaining(recoveryFragment)])
}
})
})
it('adds computer-use startup recovery steps for missing desktop apps', () => {
const error = new Error('app not found: Gmail')
Object.assign(error, { code: 'app_not_found' })
const response = mapRuntimeError('req_1', { runtimeId: 'runtime-1' }, error)
expect(response.error).toMatchObject({
code: 'app_not_found',
message: 'app not found: Gmail',
data: {
nextSteps: [
expect.stringContaining('list-apps'),
expect.stringContaining('desktop browser app/window'),
expect.stringContaining('--app <web app>'),
expect.stringContaining('list-windows --app <browser>')
]
}
})
})
it('adds computer-use recovery steps for missing desktop windows', () => {
const error = new Error('No top-level window found')
Object.assign(error, { code: 'window_not_found' })
const response = mapRuntimeError('req_1', { runtimeId: 'runtime-1' }, error)
expect(response.error).toMatchObject({
code: 'window_not_found',
data: {
nextSteps: [
expect.stringContaining('list-windows'),
expect.stringContaining('--restore-window'),
expect.stringContaining('does not launch closed desktop apps')
]
}
})
})
it('preserves structured computer-use focus error codes for CLI recovery hints', () => {
const error = new Error(
'keyboard input requires the target window to be focused; retry with --restore-window'
)
Object.assign(error, { code: 'window_not_focused' })
const response = mapRuntimeError('req_1', { runtimeId: 'runtime-1' }, error)
expect(response).toEqual({
id: 'req_1',
ok: false,
error: {
code: 'window_not_focused',
message:
'keyboard input requires the target window to be focused; retry with --restore-window',
data: {
nextSteps: [
'Retry once with `--restore-window`.',
'If `--restore-window` was already used, stop retrying restore; bring the app forward manually, check permissions, or prefer `set-value` for editable fields.'
]
}
},
_meta: { runtimeId: 'runtime-1' }
})
})
it('preserves structured lineage error codes and data for CLI recovery hints', () => {
const response = mapRuntimeError(
'req_1',
+5 -1
View File
@@ -3,6 +3,7 @@
// format human-facing messages. Centralizing this mapping keeps the allowlist
// auditable in one place instead of spread across per-method branches.
import type { RpcEnvelopeMeta, RpcFailure, RpcSuccess } from './core'
import { computerUseErrorRecoveryData } from '../../../shared/computer-use-error-recovery'
import { COMPUTER_ERROR_CODES } from '../../../shared/runtime-types'
export function successResponse(id: string, meta: RpcEnvelopeMeta, result: unknown): RpcSuccess {
@@ -57,7 +58,8 @@ export function mapRuntimeError(id: string, meta: RpcEnvelopeMeta, error: unknow
typeof (error as { code: unknown }).code === 'string' &&
COMPUTER_PASSTHROUGH_CODES.has((error as { code: string }).code)
) {
return errorResponse(id, meta, (error as { code: string }).code, message)
const code = (error as { code: string }).code
return errorResponse(id, meta, code, message, computerErrorData(code))
}
if (
error instanceof Error &&
@@ -82,6 +84,8 @@ export function mapRuntimeError(id: string, meta: RpcEnvelopeMeta, error: unknow
return errorResponse(id, meta, 'runtime_error', message)
}
export const computerErrorData = computerUseErrorRecoveryData
// Why: browser errors carry a structured .code property (BrowserError from
// cdp-bridge.ts) that maps directly to agent-facing error codes. We forward
// that code rather than falling back to the runtime allowlist, because the
@@ -0,0 +1,239 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const computerMocks = vi.hoisted(() => ({
callComputerSidecarAction: vi.fn(),
callComputerSidecarCapabilities: vi.fn(),
callComputerSidecarListApps: vi.fn(),
callComputerSidecarListWindows: vi.fn(),
callComputerSidecarSnapshot: vi.fn(),
resetComputerSidecarForTest: vi.fn(),
openComputerUsePermissions: vi.fn(),
getComputerUsePermissionStatus: vi.fn()
}))
vi.mock('../../../computer/sidecar-client', () => ({
callComputerSidecarAction: computerMocks.callComputerSidecarAction,
callComputerSidecarCapabilities: computerMocks.callComputerSidecarCapabilities,
callComputerSidecarListApps: computerMocks.callComputerSidecarListApps,
callComputerSidecarListWindows: computerMocks.callComputerSidecarListWindows,
callComputerSidecarSnapshot: computerMocks.callComputerSidecarSnapshot,
resetComputerSidecarForTest: computerMocks.resetComputerSidecarForTest
}))
vi.mock('../../../computer/macos-computer-use-permissions', () => ({
openComputerUsePermissions: computerMocks.openComputerUsePermissions,
getComputerUsePermissionStatus: computerMocks.getComputerUsePermissionStatus
}))
import { COMPUTER_METHODS, resetComputerSessionsForTest } from './computer'
describe('computer action RPC methods', () => {
beforeEach(() => {
computerMocks.callComputerSidecarAction.mockReset()
computerMocks.callComputerSidecarCapabilities.mockReset()
computerMocks.callComputerSidecarListApps.mockReset()
computerMocks.callComputerSidecarListWindows.mockReset()
computerMocks.callComputerSidecarSnapshot.mockReset()
computerMocks.resetComputerSidecarForTest.mockReset()
computerMocks.openComputerUsePermissions.mockReset()
computerMocks.getComputerUsePermissionStatus.mockReset()
resetComputerSessionsForTest()
computerMocks.resetComputerSidecarForTest.mockClear()
})
it('rejects incomplete pointer action coordinates', () => {
expect(() => findMethod('computer.click').params!.parse({ app: 'Finder' })).toThrow(
/Click requires/
)
expect(() => findMethod('computer.click').params!.parse({ app: 'Finder', x: 1 })).toThrow(
/both --x and --y/
)
expect(() =>
findMethod('computer.click').params!.parse({ app: 'Finder', elementIndex: 0, x: 1, y: 2 })
).toThrow(/either --element-index or coordinate flags/)
expect(() =>
findMethod('computer.scroll').params!.parse({ app: 'Finder', direction: 'down' })
).toThrow(/Scroll requires/)
expect(() =>
findMethod('computer.scroll').params!.parse({
app: 'Finder',
elementIndex: 0,
x: 1,
y: 2,
direction: 'down'
})
).toThrow(/either --element-index or coordinate flags/)
expect(() =>
findMethod('computer.drag').params!.parse({ app: 'Finder', fromX: 1, fromY: 2 })
).toThrow(/Drag coordinates/)
expect(() =>
findMethod('computer.drag').params!.parse({ app: 'Finder', fromElementIndex: 1 })
).toThrow(/both --from-element-index and --to-element-index/)
expect(() =>
findMethod('computer.drag').params!.parse({
app: 'Finder',
fromElementIndex: 0,
toElementIndex: 1,
fromX: 1,
fromY: 2,
toX: 3,
toY: 4
})
).toThrow(/either element indexes or coordinate flags/)
})
it('rejects unsupported scroll directions', () => {
expect(() =>
findMethod('computer.scroll').params!.parse({
app: 'Finder',
elementIndex: 0,
direction: 'diagonal'
})
).toThrow()
expect(() =>
findMethod('computer.scroll').params!.parse({
app: 'Finder',
elementIndex: 0,
direction: 'down',
pages: 0
})
).toThrow()
})
it('rejects modifier chords on press-key but allows literal plus', () => {
expect(() =>
findMethod('computer.pressKey').params!.parse({
app: 'Finder',
key: 'CmdOrCtrl+V'
})
).toThrow(/Press-key accepts one key only/)
expect(
findMethod('computer.pressKey').params!.parse({
app: 'Finder',
key: '+'
})
).toMatchObject({ key: '+' })
})
it('dispatches pointer and element actions through the sidecar', async () => {
computerMocks.callComputerSidecarAction.mockResolvedValue({ ok: true })
await call('computer.click', {
app: 'Finder',
worktree: 'path:/tmp/repo',
elementIndex: 0,
clickCount: 2,
mouseButton: 'left',
noScreenshot: true
})
await call('computer.performSecondaryAction', {
app: 'Finder',
elementIndex: 0,
action: 'Raise'
})
await call('computer.drag', {
app: 'Finder',
fromX: 1,
fromY: 2,
toX: 3,
toY: 4
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(1, 'click', {
app: 'Finder',
worktree: 'path:/tmp/repo',
elementIndex: 0,
clickCount: 2,
mouseButton: 'left',
noScreenshot: true
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(
2,
'performSecondaryAction',
{
app: 'Finder',
elementIndex: 0,
action: 'Raise'
}
)
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(3, 'drag', {
app: 'Finder',
fromX: 1,
fromY: 2,
toX: 3,
toY: 4
})
})
it('dispatches keyboard and text actions through the sidecar', async () => {
computerMocks.callComputerSidecarAction.mockResolvedValue({ ok: true })
await call('computer.typeText', { app: 'Finder', text: 'hello', noScreenshot: true })
await call('computer.pressKey', { app: 'Finder', key: 'Return' })
await call('computer.hotkey', { app: 'Finder', key: 'CmdOrCtrl+L' })
await call('computer.pasteText', { app: 'Finder', text: 'long text' })
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(1, 'typeText', {
app: 'Finder',
text: 'hello',
noScreenshot: true
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(2, 'pressKey', {
app: 'Finder',
key: 'Return'
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(3, 'hotkey', {
app: 'Finder',
key: 'CmdOrCtrl+L'
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(4, 'pasteText', {
app: 'Finder',
text: 'long text'
})
})
it('dispatches scroll and setValue actions through the sidecar', async () => {
computerMocks.callComputerSidecarAction.mockResolvedValue({ ok: true })
await call('computer.scroll', {
app: 'Finder',
elementIndex: 0,
direction: 'down',
pages: 2
})
await call('computer.setValue', {
app: 'Finder',
elementIndex: 1,
value: ''
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(1, 'scroll', {
app: 'Finder',
elementIndex: 0,
direction: 'down',
pages: 2
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(2, 'setValue', {
app: 'Finder',
elementIndex: 1,
value: ''
})
})
})
function findMethod(name: string) {
const method = COMPUTER_METHODS.find((candidate) => candidate.name === name)
if (!method) {
throw new Error(`missing method ${name}`)
}
return method
}
async function call(name: string, params: Record<string, unknown>) {
const method = findMethod(name)
const parsed = method.params ? method.params.parse(params) : undefined
return await method.handler(parsed, {
runtime: { getRuntimeId: () => 'runtime-1' } as never
})
}
@@ -0,0 +1,218 @@
import { z } from 'zod'
import {
computerUseHotkeyValidationMessage,
computerUsePressKeyValidationMessage
} from '../../../../shared/computer-use-key-spec'
import {
OptionalBoolean,
OptionalFiniteNumber,
OptionalString,
requiredString,
requiredStringAllowingEmpty
} from '../schemas'
const OptionalNonNegativeInt = z.number().int().nonnegative().optional()
const OptionalPositiveInt = z.number().int().positive().optional()
const ComputerTarget = z.object({
app: requiredString('Missing app'),
session: OptionalString,
worktree: OptionalString
})
const ComputerObserveTargetBase = ComputerTarget.extend({
noScreenshot: OptionalBoolean,
restoreWindow: OptionalBoolean,
windowId: OptionalNonNegativeInt,
windowIndex: OptionalNonNegativeInt
})
function validateWindowTarget(
value: { windowId?: number; windowIndex?: number },
ctx: z.RefinementCtx
): void {
if (value.windowId !== undefined && value.windowIndex !== undefined) {
ctx.addIssue({
code: 'custom',
message: 'Window targeting accepts either --window-id or --window-index, not both'
})
}
}
function validateComputerTarget(
value: { session?: string; worktree?: string; windowId?: number; windowIndex?: number },
ctx: z.RefinementCtx
): void {
if (value.session !== undefined && value.worktree !== undefined) {
ctx.addIssue({
code: 'custom',
message: 'Computer-use targeting accepts either session or worktree, not both'
})
}
validateWindowTarget(value, ctx)
}
export const ComputerObserveTarget = ComputerObserveTargetBase.superRefine(validateComputerTarget)
export const ListApps = z.object({}).strict()
export const ListWindows = z
.object({
app: requiredString('Missing app')
})
.strict()
export const Click = ComputerObserveTargetBase.extend({
elementIndex: OptionalNonNegativeInt,
x: OptionalFiniteNumber,
y: OptionalFiniteNumber,
clickCount: OptionalPositiveInt,
mouseButton: z.enum(['left', 'right', 'middle']).optional()
}).superRefine((value, ctx) => {
validateComputerTarget(value, ctx)
const hasElement = value.elementIndex !== undefined
const hasX = value.x !== undefined
const hasY = value.y !== undefined
if (!hasElement && !(hasX && hasY)) {
ctx.addIssue({
code: 'custom',
message: 'Click requires --element-index or both --x and --y'
})
}
if (hasX !== hasY) {
ctx.addIssue({
code: 'custom',
message: 'Click coordinates require both --x and --y'
})
}
if (hasElement && (hasX || hasY)) {
ctx.addIssue({
code: 'custom',
message: 'Click accepts either --element-index or coordinate flags, not both'
})
}
})
export const PerformSecondaryAction = ComputerObserveTargetBase.extend({
elementIndex: OptionalNonNegativeInt,
action: requiredString('Missing action')
}).superRefine((value, ctx) => {
validateComputerTarget(value, ctx)
if (value.elementIndex === undefined) {
ctx.addIssue({ code: 'custom', message: 'Missing element index' })
}
})
export const Scroll = ComputerObserveTargetBase.extend({
elementIndex: OptionalNonNegativeInt,
x: OptionalFiniteNumber,
y: OptionalFiniteNumber,
direction: z.enum(['up', 'down', 'left', 'right']),
pages: z.number().positive().optional()
}).superRefine((value, ctx) => {
validateComputerTarget(value, ctx)
const hasElement = value.elementIndex !== undefined
const hasX = value.x !== undefined
const hasY = value.y !== undefined
if (!hasElement && !(hasX && hasY)) {
ctx.addIssue({
code: 'custom',
message: 'Scroll requires --element-index or both --x and --y'
})
}
if (hasX !== hasY) {
ctx.addIssue({
code: 'custom',
message: 'Scroll coordinates require both --x and --y'
})
}
if (hasElement && (hasX || hasY)) {
ctx.addIssue({
code: 'custom',
message: 'Scroll accepts either --element-index or coordinate flags, not both'
})
}
})
export const Drag = ComputerObserveTargetBase.extend({
fromElementIndex: OptionalNonNegativeInt,
toElementIndex: OptionalNonNegativeInt,
fromX: OptionalFiniteNumber,
fromY: OptionalFiniteNumber,
toX: OptionalFiniteNumber,
toY: OptionalFiniteNumber
}).superRefine((value, ctx) => {
validateComputerTarget(value, ctx)
const hasElementPair = value.fromElementIndex !== undefined && value.toElementIndex !== undefined
const hasPartialElementPair =
value.fromElementIndex !== undefined || value.toElementIndex !== undefined
const coordinateKeys = [value.fromX, value.fromY, value.toX, value.toY]
const hasCoordinatePair = coordinateKeys.every((coordinate) => coordinate !== undefined)
const hasPartialCoordinatePair = coordinateKeys.some((coordinate) => coordinate !== undefined)
if (hasElementPair && hasCoordinatePair) {
ctx.addIssue({
code: 'custom',
message: 'Drag accepts either element indexes or coordinate flags, not both'
})
}
if (!hasElementPair && !hasCoordinatePair) {
ctx.addIssue({
code: 'custom',
message: 'Drag requires --from-element-index and --to-element-index, or all coordinate flags'
})
}
if (hasPartialElementPair && !hasElementPair) {
ctx.addIssue({
code: 'custom',
message: 'Drag element targeting requires both --from-element-index and --to-element-index'
})
}
if (hasPartialCoordinatePair && !hasCoordinatePair) {
ctx.addIssue({
code: 'custom',
message: 'Drag coordinates require --from-x, --from-y, --to-x, and --to-y'
})
}
})
export const TypeText = ComputerObserveTargetBase.extend({
text: requiredString('Missing text')
}).superRefine(validateComputerTarget)
export const PressKey = ComputerObserveTargetBase.extend({
key: requiredString('Missing key')
}).superRefine((value, ctx) => {
validateComputerTarget(value, ctx)
const message = computerUsePressKeyValidationMessage(value.key)
if (message) {
ctx.addIssue({ code: 'custom', message })
}
})
export const Hotkey = ComputerObserveTargetBase.extend({
key: requiredString('Missing key')
}).superRefine((value, ctx) => {
validateComputerTarget(value, ctx)
const message = computerUseHotkeyValidationMessage(value.key)
if (message) {
ctx.addIssue({ code: 'custom', message })
}
})
export const ComputerPermissions = z.object({
id: z.enum(['accessibility', 'screenshots']).optional()
})
export const PasteText = ComputerObserveTargetBase.extend({
text: requiredString('Missing text')
}).superRefine(validateComputerTarget)
export const SetValue = ComputerObserveTargetBase.extend({
elementIndex: OptionalNonNegativeInt,
value: requiredStringAllowingEmpty('Missing value')
}).superRefine((value, ctx) => {
validateComputerTarget(value, ctx)
if (value.elementIndex === undefined) {
ctx.addIssue({ code: 'custom', message: 'Missing element index' })
}
})
+48 -150
View File
@@ -1,4 +1,3 @@
/* eslint-disable max-lines -- Why: computer RPC coverage shares one mocked registry setup across all method contracts. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { buildRegistry } from '../core'
@@ -81,6 +80,12 @@ describe('computer RPC methods', () => {
expect(computerMocks.callComputerSidecarListApps).toHaveBeenCalledWith()
})
it('rejects ignored listApps scoping params', () => {
expect(() =>
findMethod('computer.listApps').params!.parse({ worktree: 'path:/tmp/repo' })
).toThrow()
})
it('returns provider capabilities through the sidecar', async () => {
const result = { platform: 'darwin', provider: 'orca-computer-use-macos', protocolVersion: 1 }
computerMocks.callComputerSidecarCapabilities.mockResolvedValue(result)
@@ -120,13 +125,28 @@ describe('computer RPC methods', () => {
app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 },
windows: []
}
const params = { app: 'Finder', worktree: 'path:/tmp/repo' }
const params = { app: 'Finder' }
computerMocks.callComputerSidecarListWindows.mockResolvedValue(result)
await expect(call('computer.listWindows', params)).resolves.toBe(result)
expect(computerMocks.callComputerSidecarListWindows).toHaveBeenCalledWith(params)
})
it('rejects ignored listWindows scoping params', () => {
expect(() =>
findMethod('computer.listWindows').params!.parse({
app: 'Finder',
session: 'manual'
})
).toThrow()
expect(() =>
findMethod('computer.listWindows').params!.parse({
app: 'Finder',
worktree: 'path:/tmp/repo'
})
).toThrow()
})
it('gets app state through the sidecar', async () => {
const snapshot = {
snapshot: {
@@ -176,168 +196,46 @@ describe('computer RPC methods', () => {
).toThrow(/either --window-id or --window-index/)
})
it('rejects incomplete pointer action coordinates', () => {
expect(() => findMethod('computer.click').params!.parse({ app: 'Finder' })).toThrow(
/Click requires/
)
expect(() => findMethod('computer.click').params!.parse({ app: 'Finder', x: 1 })).toThrow(
/both --x and --y/
)
it('rejects ambiguous session and worktree targeting', () => {
expect(() =>
findMethod('computer.click').params!.parse({ app: 'Finder', elementIndex: 0, x: 1, y: 2 })
).toThrow(/either --element-index or coordinate flags/)
expect(() =>
findMethod('computer.scroll').params!.parse({ app: 'Finder', direction: 'down' })
).toThrow(/Scroll requires/)
expect(() =>
findMethod('computer.scroll').params!.parse({
findMethod('computer.getAppState').params!.parse({
app: 'Finder',
elementIndex: 0,
x: 1,
y: 2,
direction: 'down'
session: 'manual',
worktree: 'id:repo::/tmp/repo'
})
).toThrow(/either --element-index or coordinate flags/)
).toThrow(/either session or worktree/)
expect(() =>
findMethod('computer.drag').params!.parse({ app: 'Finder', fromX: 1, fromY: 2 })
).toThrow(/Drag coordinates/)
expect(() =>
findMethod('computer.drag').params!.parse({ app: 'Finder', fromElementIndex: 1 })
).toThrow(/both --from-element-index and --to-element-index/)
expect(() =>
findMethod('computer.drag').params!.parse({
findMethod('computer.click').params!.parse({
app: 'Finder',
fromElementIndex: 0,
toElementIndex: 1,
fromX: 1,
fromY: 2,
toX: 3,
toY: 4
session: 'manual',
worktree: 'id:repo::/tmp/repo',
elementIndex: 0
})
).toThrow(/either element indexes or coordinate flags/)
).toThrow(/either session or worktree/)
})
it('rejects unsupported scroll directions', () => {
expect(() =>
findMethod('computer.scroll').params!.parse({
it('treats empty computer-use worktree scope as absent', () => {
expect(
findMethod('computer.getAppState').params!.parse({
app: 'Finder',
elementIndex: 0,
direction: 'diagonal'
worktree: ''
})
).toThrow()
expect(() =>
findMethod('computer.scroll').params!.parse({
app: 'Finder',
elementIndex: 0,
direction: 'down',
pages: 0
})
).toThrow()
})
it('dispatches pointer and element actions through the sidecar', async () => {
computerMocks.callComputerSidecarAction.mockResolvedValue({ ok: true })
await call('computer.click', {
).toMatchObject({
app: 'Finder',
worktree: 'path:/tmp/repo',
elementIndex: 0,
clickCount: 2,
mouseButton: 'left',
noScreenshot: true
})
await call('computer.performSecondaryAction', {
app: 'Finder',
elementIndex: 0,
action: 'Raise'
})
await call('computer.drag', {
app: 'Finder',
fromX: 1,
fromY: 2,
toX: 3,
toY: 4
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(1, 'click', {
app: 'Finder',
worktree: 'path:/tmp/repo',
elementIndex: 0,
clickCount: 2,
mouseButton: 'left',
noScreenshot: true
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(
2,
'performSecondaryAction',
{
app: 'Finder',
elementIndex: 0,
action: 'Raise'
}
)
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(3, 'drag', {
app: 'Finder',
fromX: 1,
fromY: 2,
toX: 3,
toY: 4
worktree: undefined
})
})
it('dispatches keyboard and text actions through the sidecar', async () => {
computerMocks.callComputerSidecarAction.mockResolvedValue({ ok: true })
await call('computer.typeText', { app: 'Finder', text: 'hello', noScreenshot: true })
await call('computer.pressKey', { app: 'Finder', key: 'Return' })
await call('computer.hotkey', { app: 'Finder', key: 'CmdOrCtrl+L' })
await call('computer.pasteText', { app: 'Finder', text: 'long text' })
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(1, 'typeText', {
app: 'Finder',
text: 'hello',
noScreenshot: true
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(2, 'pressKey', {
app: 'Finder',
key: 'Return'
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(3, 'hotkey', {
app: 'Finder',
key: 'CmdOrCtrl+L'
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(4, 'pasteText', {
app: 'Finder',
text: 'long text'
})
})
it('dispatches scroll and setValue actions through the sidecar', async () => {
computerMocks.callComputerSidecarAction.mockResolvedValue({ ok: true })
await call('computer.scroll', {
app: 'Finder',
elementIndex: 0,
direction: 'down',
pages: 2
})
await call('computer.setValue', {
app: 'Finder',
elementIndex: 1,
value: ''
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(1, 'scroll', {
app: 'Finder',
elementIndex: 0,
direction: 'down',
pages: 2
})
expect(computerMocks.callComputerSidecarAction).toHaveBeenNthCalledWith(2, 'setValue', {
app: 'Finder',
elementIndex: 1,
value: ''
})
it('rejects malformed hotkey specs before dispatch', () => {
expect(() =>
findMethod('computer.hotkey').params!.parse({ app: 'Finder', key: 'Return' })
).toThrow(/Hotkey requires a modifier and one key/)
expect(() =>
findMethod('computer.hotkey').params!.parse({ app: 'Finder', key: 'CmdOrCtrl+Shift' })
).toThrow(/Hotkey requires a modifier and one key/)
expect(() =>
findMethod('computer.hotkey').params!.parse({ app: 'Finder', key: 'Ctrl+A+B' })
).toThrow(/Hotkey requires a modifier and one key/)
})
})
+14 -187
View File
@@ -1,4 +1,3 @@
/* eslint-disable max-lines -- Why: computer RPC schemas and sidecar dispatch stay together so provider behavior is audited in one place. */
import { z } from 'zod'
import {
callComputerSidecarAction,
@@ -10,192 +9,20 @@ import {
} from '../../../computer/sidecar-client'
import { defineMethod, type RpcMethod } from '../core'
import {
OptionalBoolean,
OptionalFiniteNumber,
OptionalPlainString,
OptionalString,
requiredStringAllowingEmpty,
requiredString
} from '../schemas'
const OptionalNonNegativeInt = z.number().int().nonnegative().optional()
const OptionalPositiveInt = z.number().int().positive().optional()
const ComputerTarget = z.object({
app: requiredString('Missing app'),
session: OptionalString,
worktree: OptionalPlainString
})
const ComputerObserveTargetBase = ComputerTarget.extend({
noScreenshot: OptionalBoolean,
restoreWindow: OptionalBoolean,
windowId: OptionalNonNegativeInt,
windowIndex: OptionalNonNegativeInt
})
function validateWindowTarget(
value: { windowId?: number; windowIndex?: number },
ctx: z.RefinementCtx
): void {
if (value.windowId !== undefined && value.windowIndex !== undefined) {
ctx.addIssue({
code: 'custom',
message: 'Window targeting accepts either --window-id or --window-index, not both'
})
}
}
const ComputerObserveTarget = ComputerObserveTargetBase.superRefine(validateWindowTarget)
const ListApps = z.object({
worktree: OptionalPlainString
})
const ListWindows = ComputerTarget
const Click = ComputerObserveTargetBase.extend({
elementIndex: OptionalNonNegativeInt,
x: OptionalFiniteNumber,
y: OptionalFiniteNumber,
clickCount: OptionalPositiveInt,
mouseButton: z.enum(['left', 'right', 'middle']).optional()
}).superRefine((value, ctx) => {
validateWindowTarget(value, ctx)
const hasElement = value.elementIndex !== undefined
const hasX = value.x !== undefined
const hasY = value.y !== undefined
if (!hasElement && !(hasX && hasY)) {
ctx.addIssue({
code: 'custom',
message: 'Click requires --element-index or both --x and --y'
})
}
if (hasX !== hasY) {
ctx.addIssue({
code: 'custom',
message: 'Click coordinates require both --x and --y'
})
}
if (hasElement && (hasX || hasY)) {
ctx.addIssue({
code: 'custom',
message: 'Click accepts either --element-index or coordinate flags, not both'
})
}
})
const PerformSecondaryAction = ComputerObserveTargetBase.extend({
elementIndex: OptionalNonNegativeInt,
action: requiredString('Missing action')
}).superRefine((value, ctx) => {
validateWindowTarget(value, ctx)
if (value.elementIndex === undefined) {
ctx.addIssue({ code: 'custom', message: 'Missing element index' })
}
})
const Scroll = ComputerObserveTargetBase.extend({
elementIndex: OptionalNonNegativeInt,
x: OptionalFiniteNumber,
y: OptionalFiniteNumber,
direction: z.enum(['up', 'down', 'left', 'right']),
pages: z.number().positive().optional()
}).superRefine((value, ctx) => {
validateWindowTarget(value, ctx)
const hasElement = value.elementIndex !== undefined
const hasX = value.x !== undefined
const hasY = value.y !== undefined
if (!hasElement && !(hasX && hasY)) {
ctx.addIssue({
code: 'custom',
message: 'Scroll requires --element-index or both --x and --y'
})
}
if (hasX !== hasY) {
ctx.addIssue({
code: 'custom',
message: 'Scroll coordinates require both --x and --y'
})
}
if (hasElement && (hasX || hasY)) {
ctx.addIssue({
code: 'custom',
message: 'Scroll accepts either --element-index or coordinate flags, not both'
})
}
})
const Drag = ComputerObserveTargetBase.extend({
fromElementIndex: OptionalNonNegativeInt,
toElementIndex: OptionalNonNegativeInt,
fromX: OptionalFiniteNumber,
fromY: OptionalFiniteNumber,
toX: OptionalFiniteNumber,
toY: OptionalFiniteNumber
}).superRefine((value, ctx) => {
validateWindowTarget(value, ctx)
const hasElementPair = value.fromElementIndex !== undefined && value.toElementIndex !== undefined
const hasPartialElementPair =
value.fromElementIndex !== undefined || value.toElementIndex !== undefined
const coordinateKeys = [value.fromX, value.fromY, value.toX, value.toY]
const hasCoordinatePair = coordinateKeys.every((coordinate) => coordinate !== undefined)
const hasPartialCoordinatePair = coordinateKeys.some((coordinate) => coordinate !== undefined)
if (hasElementPair && hasCoordinatePair) {
ctx.addIssue({
code: 'custom',
message: 'Drag accepts either element indexes or coordinate flags, not both'
})
}
if (!hasElementPair && !hasCoordinatePair) {
ctx.addIssue({
code: 'custom',
message: 'Drag requires --from-element-index and --to-element-index, or all coordinate flags'
})
}
if (hasPartialElementPair && !hasElementPair) {
ctx.addIssue({
code: 'custom',
message: 'Drag element targeting requires both --from-element-index and --to-element-index'
})
}
if (hasPartialCoordinatePair && !hasCoordinatePair) {
ctx.addIssue({
code: 'custom',
message: 'Drag coordinates require --from-x, --from-y, --to-x, and --to-y'
})
}
})
const TypeText = ComputerObserveTargetBase.extend({
text: requiredString('Missing text')
}).superRefine(validateWindowTarget)
const PressKey = ComputerObserveTargetBase.extend({
key: requiredString('Missing key')
}).superRefine(validateWindowTarget)
const Hotkey = ComputerObserveTargetBase.extend({
key: requiredString('Missing key')
}).superRefine(validateWindowTarget)
const ComputerPermissions = z.object({
id: z.enum(['accessibility', 'screenshots']).optional()
})
const PasteText = ComputerObserveTargetBase.extend({
text: requiredString('Missing text')
}).superRefine(validateWindowTarget)
const SetValue = ComputerObserveTargetBase.extend({
elementIndex: OptionalNonNegativeInt,
value: requiredStringAllowingEmpty('Missing value')
}).superRefine((value, ctx) => {
validateWindowTarget(value, ctx)
if (value.elementIndex === undefined) {
ctx.addIssue({ code: 'custom', message: 'Missing element index' })
}
})
Click,
ComputerObserveTarget,
ComputerPermissions,
Drag,
Hotkey,
ListApps,
ListWindows,
PasteText,
PerformSecondaryAction,
PressKey,
Scroll,
SetValue,
TypeText
} from './computer-schemas'
export function resetComputerSessionsForTest(): void {
resetComputerSidecarForTest()
@@ -0,0 +1,54 @@
import { describe, expect, it } from 'vitest'
import { computerUseErrorRecoveryData } from './computer-use-error-recovery'
import { COMPUTER_ERROR_CODES } from './runtime-types'
describe('computerUseErrorRecoveryData', () => {
it('covers every declared computer-use error code with actionable recovery steps', () => {
for (const code of Object.values(COMPUTER_ERROR_CODES)) {
expect(computerUseErrorRecoveryData(code), code).toMatchObject({
nextSteps: expect.arrayContaining([expect.any(String)])
})
}
})
it('points screenshot failures at permission setup or no-screenshot fallback', () => {
const recovery = computerUseErrorRecoveryData('screenshot_failed')
expect(recovery?.nextSteps).toEqual([
expect.stringContaining('--no-screenshot'),
expect.stringContaining('--id screenshots'),
expect.stringContaining('payload cap')
])
})
it('points permission failures at targeted permission setup when possible', () => {
const recovery = computerUseErrorRecoveryData('permission_denied')
expect(recovery?.nextSteps).toEqual([
expect.stringContaining('--id accessibility'),
expect.stringContaining('graphical desktop session')
])
})
it('points missing windows at list-windows before a single restore retry', () => {
const recovery = computerUseErrorRecoveryData('window_not_found')
expect(recovery?.nextSteps).toEqual([
expect.stringContaining('list-windows'),
expect.stringContaining('--restore-window'),
expect.stringContaining('does not launch closed desktop apps')
])
})
it('keeps missing web app recovery within computer-use desktop app targeting', () => {
const recovery = computerUseErrorRecoveryData('app_not_found')
expect(recovery?.nextSteps).toEqual([
expect.stringContaining('list-apps'),
expect.stringContaining('desktop browser app/window'),
expect.stringContaining('--app <web app>'),
expect.stringContaining('list-windows --app <browser>')
])
expect(recovery?.nextSteps.join('\n')).not.toContain('orca goto')
})
})
+100
View File
@@ -0,0 +1,100 @@
export type ComputerUseErrorRecoveryData = {
nextSteps: string[]
}
export function computerUseErrorRecoveryData(
code: string
): ComputerUseErrorRecoveryData | undefined {
switch (code) {
case 'app_not_found':
return recoverWith(
'Run `orca computer list-apps --json` and retry with the exact app name or bundle ID.',
'If the target is a website or web app such as Gmail, choose the desktop browser app/window that contains it; `orca computer` app selectors refer to desktop apps, not website names.',
'Do not retry the same `orca computer ... --app <web app>` command unchanged.',
'If the desired browser is not listed, open or focus that browser first, then retry `orca computer list-apps --json` and `orca computer list-windows --app <browser> --json`.'
)
case 'app_blocked':
return recoverWith(
'Do not continue with this app through computer-use; choose a non-sensitive target or ask the user to handle it manually.'
)
case 'window_not_found':
return recoverWith(
'Run `orca computer list-windows --app <app> --json` and target one of the listed windows.',
'If the app is listed but no usable window is visible, retry observation once with `--restore-window`.',
'If no window is listed, open or focus the app first; `orca computer` does not launch closed desktop apps.'
)
case 'window_not_focused':
return recoverWith(
'Retry once with `--restore-window`.',
'If `--restore-window` was already used, stop retrying restore; bring the app forward manually, check permissions, or prefer `set-value` for editable fields.'
)
case 'window_stale':
return recoverWith(
'Run `orca computer list-windows --app <app> --json` and choose a current window selector.',
'Then rerun `orca computer get-app-state --app <app> --json` before acting.'
)
case 'provider_incompatible':
return recoverWith(
'Run `orca computer capabilities --json` and verify the local provider supports the requested operation.',
'Update Orca or use a supported platform/provider path before retrying.'
)
case 'unsupported_capability':
return recoverWith(
'Run `orca computer capabilities --json` and choose a supported action.',
'Use a semantic alternative such as `set-value` or `click`, or install the missing desktop dependency if the error names one.'
)
case 'permission_denied':
return recoverWith(
'Run `orca computer permissions --json`, or `orca computer permissions --id accessibility --json` / `--id screenshots --json` when the message names one missing permission.',
'For remote or SSH targets, verify the command is running inside an active graphical desktop session.'
)
case 'element_not_found':
return recoverWith(
'Run `orca computer get-app-state --app <app> --json` again and use an element index from the fresh tree.',
'Do not infer valid indexes from `elementCount` or reuse indexes after navigation, scrolling, focus changes, or delays.'
)
case 'element_not_clickable':
return recoverWith(
'Choose a nearby parent or child element that has an actionable frame.',
'If using coordinates, derive window-local coordinates from the latest screenshot/state for the same target window.'
)
case 'action_not_supported':
return recoverWith(
'Inspect the element in a fresh `get-app-state` result and use one of its advertised secondary actions.',
'If no suitable action is listed, use `click`, `set-value`, or another semantic action instead.'
)
case 'value_not_settable':
return recoverWith(
'Choose a settable text element from a fresh `get-app-state` result.',
'If the target cannot accept direct value writes, focus it and use keyboard input only after inspecting the returned state.'
)
case 'invalid_argument':
return recoverWith(
'Fix the command flags or RPC params exactly as described by the error message.',
'Do not retry the same command unchanged.'
)
case 'action_timeout':
return recoverWith(
'Run `orca computer get-app-state --app <app> --json` before retrying so you know whether the UI changed.',
'Retry with a simpler semantic action or `--no-screenshot` if observation is slow; do not repeat the same timed-out action blindly.'
)
case 'screenshot_failed':
return recoverWith(
'If the accessibility tree is sufficient, rerun the command with `--no-screenshot` instead of retrying the same screenshot capture.',
'If the message mentions Screen Recording or screenshots permission, run `orca computer permissions --id screenshots --json` and grant access before retrying.',
'If the message mentions the payload cap, target a smaller/current window or use `--no-screenshot`.'
)
case 'accessibility_error':
return recoverWith(
'Run `orca computer capabilities --json` to confirm the provider is available before retrying.',
'If the message mentions permissions, run `orca computer permissions --id accessibility --json` and grant access.',
'Do not loop on the same action if provider availability or permissions remain unchanged.'
)
default:
return undefined
}
}
function recoverWith(...nextSteps: string[]): ComputerUseErrorRecoveryData {
return { nextSteps }
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest'
import {
computerUseHotkeyValidationMessage,
computerUsePressKeyValidationMessage
} from './computer-use-key-spec'
describe('computer-use key specs', () => {
it('accepts hotkeys with modifiers and one key', () => {
expect(computerUseHotkeyValidationMessage('CmdOrCtrl+A')).toBeNull()
expect(computerUseHotkeyValidationMessage('ctrl+shift+p')).toBeNull()
expect(computerUseHotkeyValidationMessage('CommandOrControl + Option + Space')).toBeNull()
})
it('rejects single keys, modifier-only chords, empty parts, and multiple base keys', () => {
const expected = expect.stringContaining('Hotkey requires a modifier and one key')
expect(computerUseHotkeyValidationMessage('Return')).toEqual(expected)
expect(computerUseHotkeyValidationMessage('CmdOrCtrl+Shift')).toEqual(expected)
expect(computerUseHotkeyValidationMessage('Ctrl++A')).toEqual(expected)
expect(computerUseHotkeyValidationMessage('Ctrl+A+B')).toEqual(expected)
})
it('accepts single press keys including literal plus', () => {
expect(computerUsePressKeyValidationMessage('Return')).toBeNull()
expect(computerUsePressKeyValidationMessage('PageUp')).toBeNull()
expect(computerUsePressKeyValidationMessage('+')).toBeNull()
})
it('rejects modifier chords on the press-key path', () => {
const expected = expect.stringContaining('Press-key accepts one key only')
expect(computerUsePressKeyValidationMessage('CmdOrCtrl+V')).toEqual(expected)
expect(computerUsePressKeyValidationMessage('Ctrl+Shift+P')).toEqual(expected)
expect(computerUsePressKeyValidationMessage('')).toEqual(expected)
})
})
+54
View File
@@ -0,0 +1,54 @@
const HOTKEY_MODIFIERS = new Set([
'alt',
'cmd',
'cmdorctrl',
'command',
'commandorcontrol',
'control',
'ctrl',
'meta',
'option',
'shift',
'super',
'win'
])
const HOTKEY_HINT =
'Hotkey requires a modifier and one key, e.g. CmdOrCtrl+A. Use press-key for a single key.'
const PRESS_KEY_HINT =
'Press-key accepts one key only, e.g. Return, Escape, Tab, or +. Use hotkey for modifier combinations.'
export function computerUseHotkeyValidationMessage(key: string): string | null {
const parts = key.split('+').map((part) => part.trim())
if (parts.length < 2 || parts.some((part) => part.length === 0)) {
return HOTKEY_HINT
}
let keyPartCount = 0
for (const part of parts) {
if (!HOTKEY_MODIFIERS.has(normalizeHotkeyPart(part))) {
keyPartCount += 1
}
}
if (keyPartCount !== 1) {
return HOTKEY_HINT
}
return null
}
export function computerUsePressKeyValidationMessage(key: string): string | null {
const trimmed = key.trim()
if (trimmed.length === 0) {
return PRESS_KEY_HINT
}
if (trimmed !== '+' && trimmed.includes('+')) {
return PRESS_KEY_HINT
}
return null
}
function normalizeHotkeyPart(part: string): string {
return part.toLowerCase().replace(/[\s_-]/g, '')
}
+49 -7
View File
@@ -145,6 +145,40 @@ describe('sendRemoteRuntimeRequest', () => {
})
})
it('preserves structured failure data for remote computer-use recovery hints', async () => {
const server = await createOneShotServer({
response: (requestId) => ({
id: requestId,
ok: false,
error: {
code: 'app_not_found',
message: 'app not found: Gmail',
data: {
nextSteps: ['Target the desktop browser app/window that contains Gmail.']
}
},
_meta: { runtimeId: 'runtime-test' }
})
})
const response = await sendRemoteRuntimeRequest(
server.pairing,
'computer.getAppState',
{ app: 'Gmail' },
1000
)
expect(response).toMatchObject({
ok: false,
error: {
code: 'app_not_found',
data: {
nextSteps: [expect.stringContaining('desktop browser app/window')]
}
}
})
})
it('detaches one-shot socket listeners after a successful response', async () => {
const offSpy = vi.spyOn(WebSocketClient.prototype, 'off')
try {
@@ -258,7 +292,11 @@ function sendEncrypted(ws: WebSocket, sharedKey: Uint8Array, message: unknown):
ws.send(encrypt(JSON.stringify(message), sharedKey))
}
async function createOneShotServer(): Promise<{ pairing: PairingOffer }> {
async function createOneShotServer(
options: {
response?: (requestId: string) => unknown
} = {}
): Promise<{ pairing: PairingOffer }> {
const serverKeyPair = generateKeyPair()
const wss = new WebSocketServer({ port: 0 })
servers.push(wss)
@@ -300,12 +338,16 @@ async function createOneShotServer(): Promise<{ pairing: PairingOffer }> {
ws.once('close', () => clearInterval(keepalive))
setTimeout(() => {
clearInterval(keepalive)
sendEncrypted(ws, key, {
id: request.id,
ok: true,
result: { satisfied: true },
_meta: { runtimeId: 'runtime-test' }
})
sendEncrypted(
ws,
key,
options.response?.(request.id) ?? {
id: request.id,
ok: true,
result: { satisfied: true },
_meta: { runtimeId: 'runtime-test' }
}
)
}, 550)
})
})
+12 -12
View File
@@ -801,6 +801,7 @@ export const COMPUTER_ERROR_CODES = {
app_not_found: 'app_not_found',
app_blocked: 'app_blocked',
window_not_found: 'window_not_found',
window_not_focused: 'window_not_focused',
window_stale: 'window_stale',
provider_incompatible: 'provider_incompatible',
unsupported_capability: 'unsupported_capability',
@@ -819,16 +820,6 @@ export type ComputerErrorCode = keyof typeof COMPUTER_ERROR_CODES
export type ComputerAppQuery = string
export type ComputerSessionTarget = {
session?: string
worktree?: string
app?: ComputerAppQuery
}
export type ComputerListAppsArgs = {
worktree?: string
}
export type ComputerAppInfo = {
name: string
bundleId: string | null
@@ -837,6 +828,7 @@ export type ComputerAppInfo = {
export type ComputerWindowInfo = {
id?: number | null
index?: number | null
title: string
x?: number | null
y?: number | null
@@ -895,19 +887,27 @@ export type ComputerActionMetadata = {
actionName?: string | null
fallbackReason?: string | null
targetWindowId?: number | null
targetWindowIndex?: number | null
verification?: ComputerActionVerification
}
export type ComputerActionVerification =
| {
state: 'verified'
property: 'focusedText' | 'selection'
property: 'focusedText' | 'selection' | 'value'
expected?: string | null
actualPreview?: string | null
}
| {
state: 'unverified'
reason: 'synthetic_input' | 'clipboard_paste' | 'provider_unavailable' | 'window_changed'
reason:
| 'synthetic_input'
| 'clipboard_paste'
| 'provider_unavailable'
| 'window_changed'
| 'value_mismatch'
expected?: string | null
actualPreview?: string | null
}
export type ComputerSnapshotResult = {
+60 -1
View File
@@ -1,7 +1,9 @@
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import type { ComputerActionResult, ComputerSnapshotResult } from '../../src/shared/runtime-types'
import {
ensureOrcaRuntimeLaunched,
ensureGeditLaunched,
findRoleIndex,
killGedit,
parseJsonOutput,
runOrcaCli
@@ -12,6 +14,7 @@ const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1'
describe.skipIf(!isLinux || !e2eOptIn)('computer-use Linux e2e (gedit)', () => {
beforeAll(async () => {
await ensureOrcaRuntimeLaunched()
await ensureGeditLaunched()
})
@@ -27,7 +30,59 @@ describe.skipIf(!isLinux || !e2eOptIn)('computer-use Linux e2e (gedit)', () => {
expect(envelope.result.snapshot.coordinateSpace).toBe('window')
expect(envelope.result.snapshot.truncation?.truncated).toBe(false)
expect(envelope.result.screenshot?.data).toBeUndefined()
expect(envelope.result.screenshot?.path).toContain('orca-computer-use-')
expect(envelope.result.screenshot?.path).toContain('orca-computer-use')
})
test('click and type-text send synthetic input to the document', async () => {
const before = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(
await runOrcaCli([
'computer',
'get-app-state',
'--app',
'gedit',
'--restore-window',
'--no-screenshot',
'--json'
])
).stdout
)
const textIndex = findRoleIndex(
before.result.snapshot.treeText,
/^\s*(\d+)\s+(text|text entry|entry|document|edit area)(?:\s|$)/im
)
expect(textIndex).toBeGreaterThanOrEqual(0)
await runOrcaCli([
'computer',
'click',
'--app',
'gedit',
'--element-index',
String(textIndex),
'--restore-window',
'--no-screenshot',
'--json'
])
const marker = ` orca-linux-type-${Date.now()}`
const typed = parseJsonOutput<{ result: ComputerActionResult }>(
(
await runOrcaCli([
'computer',
'type-text',
'--app',
'gedit',
'--text',
marker,
'--restore-window',
'--no-screenshot',
'--json'
])
).stdout
)
expect(typed.result.action?.path).toBe('synthetic')
expect(typed.result.snapshot.treeText).toContain(marker.trim())
})
test('paste-text mutates the test-owned document', async () => {
@@ -48,6 +103,10 @@ describe.skipIf(!isLinux || !e2eOptIn)('computer-use Linux e2e (gedit)', () => {
).stdout
)
expect(action.result.action?.path).toBe('clipboard')
expect(action.result.action?.verification).toMatchObject({
state: 'unverified',
reason: 'clipboard_paste'
})
const after = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(
+183
View File
@@ -0,0 +1,183 @@
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import type {
ComputerActionResult,
ComputerListWindowsResult,
ComputerSnapshotResult
} from '../../src/shared/runtime-types'
import {
closeSafariDraftFixture,
ensureOrcaRuntimeLaunched,
ensureSafariDraftFixtureLaunched,
findRoleIndex,
parseJsonOutput,
runOrcaCli,
type SafariDraftFixture
} from './helpers/computer-driver'
const isMac = process.platform === 'darwin'
const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1'
describe.skipIf(!isMac || !e2eOptIn)('computer-use macOS e2e (Safari web app)', () => {
let fixture: SafariDraftFixture
beforeAll(async () => {
await ensureOrcaRuntimeLaunched()
fixture = await ensureSafariDraftFixtureLaunched()
})
afterAll(async () => {
await closeSafariDraftFixture()
})
test('fills a browser-hosted draft using fresh state between actions', async () => {
const targetArgs = await safariFixtureWindowTargetArgs(fixture.title)
let state = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(
await runOrcaCli([
'computer',
'get-app-state',
'--app',
'com.apple.Safari',
...targetArgs,
'--restore-window',
'--no-screenshot',
'--json'
])
).stdout
)
expect(state.result.snapshot.window.title).toContain(fixture.title)
expect(state.result.snapshot.treeText).toContain('Draft empty')
const recipientIndex = findRoleIndex(
state.result.snapshot.treeText,
/^\s*(\d+)\s+text field \(settable\) Recipient/m
)
expect(recipientIndex).toBeGreaterThanOrEqual(0)
await runOrcaCli([
'computer',
'click',
'--app',
'com.apple.Safari',
...targetArgs,
'--element-index',
String(recipientIndex),
'--restore-window',
'--no-screenshot',
'--json'
])
const recipient = `agent-${Date.now()}@example.com`
const recipientPaste = parseJsonOutput<{ result: ComputerActionResult }>(
(
await runOrcaCli([
'computer',
'paste-text',
'--app',
'com.apple.Safari',
...targetArgs,
'--text',
recipient,
'--restore-window',
'--no-screenshot',
'--json'
])
).stdout
)
expect(recipientPaste.result.action?.verification).toMatchObject({
state: 'verified',
property: 'focusedText',
expected: recipient
})
state = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(
await runOrcaCli([
'computer',
'press-key',
'--app',
'com.apple.Safari',
...targetArgs,
'--key',
'Tab',
'--restore-window',
'--no-screenshot',
'--json'
])
).stdout
)
expect(state.result.snapshot.treeText).toContain('focused UI element is')
expect(state.result.snapshot.treeText).toContain('Body')
const body = `hello browser draft ${Date.now()}`
const bodyPaste = parseJsonOutput<{ result: ComputerActionResult }>(
(
await runOrcaCli([
'computer',
'paste-text',
'--app',
'com.apple.Safari',
...targetArgs,
'--text',
body,
'--restore-window',
'--no-screenshot',
'--json'
])
).stdout
)
expect(bodyPaste.result.action?.verification).toMatchObject({
state: 'verified',
property: 'focusedText',
expected: body
})
state = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(
await runOrcaCli([
'computer',
'get-app-state',
'--app',
'com.apple.Safari',
...targetArgs,
'--restore-window',
'--no-screenshot',
'--json'
])
).stdout
)
const saveIndex = findRoleIndex(state.result.snapshot.treeText, 'button Save draft')
expect(saveIndex).toBeGreaterThanOrEqual(0)
const saved = parseJsonOutput<{ result: ComputerActionResult }>(
(
await runOrcaCli([
'computer',
'click',
'--app',
'com.apple.Safari',
...targetArgs,
'--element-index',
String(saveIndex),
'--restore-window',
'--no-screenshot',
'--json'
])
).stdout
)
expect(saved.result.action?.actionName).toBe('AXPress')
expect(saved.result.snapshot.treeText).toContain(`Draft ready: ${recipient} / ${body}`)
})
})
async function safariFixtureWindowTargetArgs(title: string): Promise<string[]> {
const windows = parseJsonOutput<{ result: ComputerListWindowsResult }>(
(await runOrcaCli(['computer', 'list-windows', '--app', 'com.apple.Safari', '--json'])).stdout
).result.windows
const target = windows.find((window) => window.title.includes(title))
expect(target).toBeTruthy()
if (target?.id !== undefined && target.id !== null) {
return ['--window-id', String(target.id)]
}
return ['--window-index', String(target?.index ?? 0)]
}
+3 -1
View File
@@ -6,6 +6,7 @@ import type {
} from '../../src/shared/runtime-types'
import {
activateFinder,
ensureOrcaRuntimeLaunched,
ensureTextEditLaunched,
findRoleIndex,
killTextEdit,
@@ -18,6 +19,7 @@ const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1'
describe.skipIf(!isMac || !e2eOptIn)('computer-use macOS e2e (TextEdit)', () => {
beforeAll(async () => {
await ensureOrcaRuntimeLaunched()
await ensureTextEditLaunched()
})
@@ -247,6 +249,6 @@ describe.skipIf(!isMac || !e2eOptIn)('computer-use macOS e2e (TextEdit)', () =>
expect(envelope.result.screenshot?.format).toBe('png')
expect(envelope.result.screenshot?.data).toBeUndefined()
expect(envelope.result.screenshot?.dataOmitted).toBe(true)
expect(envelope.result.screenshot?.path).toContain('orca-computer-use-')
expect(envelope.result.screenshot?.path).toContain('orca-computer-use')
})
})
+12 -8
View File
@@ -1,12 +1,19 @@
import { describe, expect, test } from 'vitest'
import type { ComputerListAppsResult, ComputerSnapshotResult } from '../../src/shared/runtime-types'
import { findRoleIndex, parseJsonOutput, runOrcaCli } from './helpers/computer-driver'
import {
ensureOrcaRuntimeLaunched,
findRoleIndex,
parseJsonOutput,
runOrcaCli,
stopOrcaRuntime
} from './helpers/computer-driver'
const isWindows = process.platform === 'win32'
const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1'
describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Store apps)', () => {
test('Store app windows are discoverable by title and clickable', async () => {
await ensureOrcaRuntimeLaunched()
await launchCalculator()
try {
const apps = parseJsonOutput<{ result: ComputerListAppsResult }>(
@@ -30,13 +37,9 @@ describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Store apps)'
])
).stdout
)
const one = findRoleIndex(state.result.snapshot.treeText, 'button One')
const plus = findRoleIndex(state.result.snapshot.treeText, 'button Plus')
const two = findRoleIndex(state.result.snapshot.treeText, 'button Two')
const equals = findRoleIndex(state.result.snapshot.treeText, 'button Equals')
expect([one, plus, two, equals].every((index) => index >= 0)).toBe(true)
for (const index of [one, plus, two, equals]) {
for (const buttonName of ['One', 'Plus', 'Two', 'Equals']) {
const index = findRoleIndex(state.result.snapshot.treeText, `button ${buttonName}`)
expect(index).toBeGreaterThanOrEqual(0)
state = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(
await runOrcaCli([
@@ -55,6 +58,7 @@ describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Store apps)'
expect(state.result.snapshot.treeText).toMatch(/Display is 3\b/)
} finally {
await killCalculator()
await stopOrcaRuntime()
}
})
})
+25 -73
View File
@@ -6,34 +6,39 @@ import type {
ComputerSnapshotResult
} from '../../src/shared/runtime-types'
import {
ensureOrcaRuntimeLaunched,
ensureNotepadLaunched,
findRoleIndex,
getNotepadAppSelector,
killNotepad,
parseJsonOutput,
runOrcaCli
runOrcaCli,
stopOrcaRuntime
} from './helpers/computer-driver'
const isWindows = process.platform === 'win32'
const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1'
const editableRolePattern = /^\s*(\d+)\s+(document|edit|text|pane)(?:\s|$)/im
describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Notepad)', () => {
beforeAll(async () => {
await ensureOrcaRuntimeLaunched()
await ensureNotepadLaunched()
})
afterAll(async () => {
await killNotepad()
await stopOrcaRuntime()
})
test('list-apps includes the test-owned Notepad process', async () => {
const result = await runOrcaCli(['computer', 'list-apps', '--json'])
const envelope = parseJsonOutput<{ result: ComputerListAppsResult }>(result.stdout)
const pid = Number.parseInt(getNotepadAppSelector().slice(4), 10)
const notepadApp = envelope.result.apps.find((app) => app.pid === pid)
expect(envelope.result.apps).toEqual(
expect.arrayContaining([expect.objectContaining({ name: 'Notepad', pid })])
)
expect(notepadApp).toMatchObject({ pid, bundleId: 'notepad' })
expect(notepadApp?.name.toLowerCase()).toBe('notepad')
})
test('list-windows returns a targetable Notepad window', async () => {
@@ -41,16 +46,15 @@ describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Notepad)', (
const result = await runOrcaCli(['computer', 'list-windows', '--app', app, '--json'])
const envelope = parseJsonOutput<{ result: ComputerListWindowsResult }>(result.stdout)
expect(envelope.result.windows).toEqual([
expect.objectContaining({
index: 0,
app: expect.objectContaining({ name: 'Notepad' }),
id: expect.any(Number),
title: expect.stringContaining('Notepad'),
width: expect.any(Number),
height: expect.any(Number)
})
])
expect(envelope.result.windows).toHaveLength(1)
expect(envelope.result.windows[0]).toMatchObject({
index: 0,
app: expect.objectContaining({ pid: Number.parseInt(app.slice(4), 10) }),
id: expect.any(Number),
title: expect.stringContaining('Notepad'),
width: expect.any(Number),
height: expect.any(Number)
})
})
test('Notepad exposes a basic accessibility tree', async () => {
@@ -63,7 +67,7 @@ describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Notepad)', (
])
const envelope = parseJsonOutput<{ result: ComputerSnapshotResult }>(result.stdout)
expect(envelope.result.snapshot.app.name).toBe('Notepad')
expect(envelope.result.snapshot.app.name.toLowerCase()).toBe('notepad')
expect(envelope.result.snapshot.window.title).toContain('Notepad')
expect(envelope.result.snapshot.elementCount).toBeGreaterThan(0)
expect(envelope.result.snapshot.coordinateSpace).toBe('window')
@@ -75,37 +79,6 @@ describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Notepad)', (
expect(envelope.result.screenshot?.path).toContain('orca-computer-use')
})
test('set-value mutates the document through UI Automation', async () => {
const app = getNotepadAppSelector()
const before = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(await runOrcaCli(['computer', 'get-app-state', '--app', app, '--no-screenshot', '--json']))
.stdout
)
const documentIndex = findRoleIndex(before.result.snapshot.treeText, 'document')
expect(documentIndex).toBeGreaterThanOrEqual(0)
const marker = `orca-windows-set-${Date.now()}`
const action = parseJsonOutput<{ result: ComputerActionResult }>(
(
await runOrcaCli([
'computer',
'set-value',
'--app',
app,
'--element-index',
String(documentIndex),
'--value',
marker,
'--no-screenshot',
'--json'
])
).stdout
)
expect(action.result.action?.path).toBe('accessibility')
expect(action.result.snapshot.treeText).toContain(marker)
})
test('paste-text mutates the test-owned document', async () => {
const app = getNotepadAppSelector()
const marker = `orca-windows-paste-${Date.now()}`
@@ -125,6 +98,10 @@ describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Notepad)', (
).stdout
)
expect(action.result.action?.path).toBe('clipboard')
expect(action.result.action?.verification).toMatchObject({
state: 'unverified',
reason: 'clipboard_paste'
})
const after = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(await runOrcaCli(['computer', 'get-app-state', '--app', app, '--no-screenshot', '--json']))
@@ -133,34 +110,9 @@ describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Notepad)', (
expect(after.result.snapshot.treeText).toContain(marker)
})
test('Unicode payloads survive set-value and paste-text', async () => {
test('Unicode payloads survive paste-text', async () => {
const app = getNotepadAppSelector()
const before = parseJsonOutput<{ result: ComputerSnapshotResult }>(
(await runOrcaCli(['computer', 'get-app-state', '--app', app, '--no-screenshot', '--json']))
.stdout
)
const documentIndex = findRoleIndex(before.result.snapshot.treeText, 'document')
expect(documentIndex).toBeGreaterThanOrEqual(0)
const unicode = `orca unicode café Ω 漢字 ${Date.now()}`
const set = parseJsonOutput<{ result: ComputerActionResult }>(
(
await runOrcaCli([
'computer',
'set-value',
'--app',
app,
'--element-index',
String(documentIndex),
'--value',
unicode,
'--no-screenshot',
'--json'
])
).stdout
)
expect(set.result.snapshot.treeText).toContain(unicode)
const pasted = parseJsonOutput<{ result: ComputerActionResult }>(
(
await runOrcaCli([
@@ -237,7 +189,7 @@ describe.skipIf(!isWindows || !e2eOptIn)('computer-use Windows e2e (Notepad)', (
(await runOrcaCli(['computer', 'get-app-state', '--app', app, '--no-screenshot', '--json']))
.stdout
)
const documentIndex = findRoleIndex(before.result.snapshot.treeText, 'document')
const documentIndex = findRoleIndex(before.result.snapshot.treeText, editableRolePattern)
expect(documentIndex).toBeGreaterThanOrEqual(0)
await runOrcaCli([
+181
View File
@@ -0,0 +1,181 @@
import { execFile, spawn, type ChildProcess } from 'child_process'
import { access, mkdtemp } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import { promisify } from 'util'
const execFileAsync = promisify(execFile)
const RUNTIME_METADATA_FILE = 'orca-runtime.json'
let orcaDevUserDataPath: string | null = null
let orcaServeProcess: ChildProcess | null = null
let orcaServeStdout = ''
let orcaServeStderr = ''
export type CliResult = {
stdout: string
stderr: string
}
type RunOrcaCliOptions = {
retryMissingRuntimeMetadata?: boolean
}
export async function runOrcaCli(
args: string[],
options: RunOrcaCliOptions = {}
): Promise<CliResult> {
try {
return await runOrcaCliOnce(args)
} catch (error) {
if (
options.retryMissingRuntimeMetadata !== false &&
isMissingRuntimeMetadataError(args, error)
) {
// Why: Windows CI can let the dev runtime exit while launching the
// fixture app; reopen once so the desktop action gets a live runtime.
await ensureOrcaRuntimeLaunched()
return await runOrcaCliOnce(args)
}
throw error
}
}
async function runOrcaCliOnce(args: string[]): Promise<CliResult> {
const devCli = join(process.cwd(), 'config/scripts/orca-dev.mjs')
const command = process.env.ORCA_COMPUTER_CLI ?? process.execPath
const cliArgs = process.env.ORCA_COMPUTER_CLI ? args : [devCli, ...args]
const env = { ...process.env }
if (!process.env.ORCA_COMPUTER_CLI && !env.ORCA_DEV_USER_DATA_PATH) {
env.ORCA_DEV_USER_DATA_PATH = await getComputerE2eOrcaDevUserDataPath()
}
try {
const result = await execFileAsync(command, cliArgs, {
env,
maxBuffer: 20 * 1024 * 1024
})
return { stdout: result.stdout, stderr: result.stderr }
} catch (error) {
if (error && typeof error === 'object' && 'stdout' in error && 'stderr' in error) {
const output = error as { message: string; stdout: string; stderr: string }
throw new Error(`${output.message}\nstdout:\n${output.stdout}\nstderr:\n${output.stderr}`)
}
throw error
}
}
export async function ensureOrcaRuntimeLaunched(): Promise<void> {
if (!process.env.ORCA_COMPUTER_CLI && process.platform === 'win32') {
await ensureOrcaRuntimeServed()
return
}
await runOrcaCli(['open', '--json'], { retryMissingRuntimeMetadata: false })
await waitForOrcaRuntimeReady()
}
export async function stopOrcaRuntime(): Promise<void> {
const processToStop = orcaServeProcess
if (!processToStop?.pid) {
return
}
orcaServeProcess = null
if (process.platform === 'win32') {
try {
await execFileAsync('taskkill.exe', ['/PID', String(processToStop.pid), '/T', '/F'])
} catch {
// The foreground test runtime may already have exited.
}
return
}
processToStop.kill()
}
export function parseJsonOutput<T>(stdout: string): T {
return JSON.parse(stdout) as T
}
async function getComputerE2eOrcaDevUserDataPath(): Promise<string> {
if (!orcaDevUserDataPath) {
// Why: the shared orca-dev profile can keep an older runtime alive across
// local test runs, making computer-use E2E exercise stale provider code.
orcaDevUserDataPath = await mkdtemp(join(tmpdir(), 'orca-computer-runtime-'))
}
return orcaDevUserDataPath
}
async function waitForOrcaRuntimeReady(): Promise<void> {
const userDataPath = await getComputerE2eOrcaDevUserDataPath()
const metadataPath = join(userDataPath, RUNTIME_METADATA_FILE)
const deadline = Date.now() + 15000
let lastError: unknown = null
while (Date.now() < deadline) {
try {
await access(metadataPath)
const status = parseJsonOutput<{
result: { runtime: { reachable: boolean } }
}>((await runOrcaCli(['status', '--json'], { retryMissingRuntimeMetadata: false })).stdout)
if (status.result.runtime.reachable) {
return
}
} catch (error) {
lastError = error
}
await delay(250)
}
const detail = [
lastError instanceof Error ? `Last error: ${lastError.message}` : null,
orcaServeStdout.trim() ? `serve stdout: ${orcaServeStdout.trim()}` : null,
orcaServeStderr.trim() ? `serve stderr: ${orcaServeStderr.trim()}` : null
]
.filter(Boolean)
.join(' ')
throw new Error(`Orca runtime metadata was not ready at ${metadataPath}.${detail}`)
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function ensureOrcaRuntimeServed(): Promise<void> {
if (!orcaServeProcess || orcaServeProcess.exitCode !== null) {
const devCli = join(process.cwd(), 'config/scripts/orca-dev.mjs')
const env = {
...process.env,
ORCA_DEV_USER_DATA_PATH: await getComputerE2eOrcaDevUserDataPath()
}
orcaServeStdout = ''
orcaServeStderr = ''
orcaServeProcess = spawn(process.execPath, [devCli, 'serve', '--no-pairing', '--json'], {
env,
windowsHide: true
})
orcaServeProcess.stdout?.on('data', (chunk) => {
orcaServeStdout += String(chunk)
})
orcaServeProcess.stderr?.on('data', (chunk) => {
orcaServeStderr += String(chunk)
})
orcaServeProcess.once('exit', () => {
orcaServeProcess = null
})
process.once('exit', () => {
orcaServeProcess?.kill()
})
}
await waitForOrcaRuntimeReady()
}
function isMissingRuntimeMetadataError(args: string[], error: unknown): boolean {
if (args[0] !== 'computer') {
return false
}
if (!error || typeof error !== 'object' || !('message' in error)) {
return false
}
const message = String((error as { message?: unknown }).message)
return (
message.includes('"code": "runtime_unavailable"') &&
message.includes('Could not read Orca runtime metadata')
)
}
+149 -36
View File
@@ -3,51 +3,35 @@ import { mkdtemp, rm, writeFile } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import { promisify } from 'util'
import {
ensureOrcaRuntimeLaunched,
parseJsonOutput,
runOrcaCli,
stopOrcaRuntime,
type CliResult
} from './computer-cli-driver'
const execFileAsync = promisify(execFile)
let textEditTempDir: string | null = null
let safariDraftTempDir: string | null = null
let safariDraftTitle: string | null = null
let linuxTempDir: string | null = null
let windowsTempDir: string | null = null
let geditProcess: ChildProcess | null = null
let notepadProcess: ChildProcess | null = null
let notepadAppSelector: string | null = null
export type CliResult = {
stdout: string
stderr: string
}
export async function runOrcaCli(args: string[]): Promise<CliResult> {
const devCli = join(process.cwd(), 'config/scripts/orca-dev')
const builtCli = join(process.cwd(), 'out/cli/index.js')
const command =
process.env.ORCA_COMPUTER_CLI ?? (process.platform === 'win32' ? process.execPath : devCli)
const cliArgs = process.env.ORCA_COMPUTER_CLI
? args
: process.platform === 'win32'
? [builtCli, ...args]
: args
try {
const result = await execFileAsync(command, cliArgs, {
maxBuffer: 20 * 1024 * 1024
})
return { stdout: result.stdout, stderr: result.stderr }
} catch (error) {
if (error && typeof error === 'object' && 'stdout' in error && 'stderr' in error) {
const output = error as { message: string; stdout: string; stderr: string }
throw new Error(`${output.message}\nstdout:\n${output.stdout}\nstderr:\n${output.stderr}`)
}
throw error
}
}
export { ensureOrcaRuntimeLaunched, parseJsonOutput, runOrcaCli, stopOrcaRuntime, type CliResult }
export async function ensureTextEditLaunched(): Promise<void> {
await killTextEdit()
textEditTempDir = await mkdtemp(join(tmpdir(), 'orca-computer-e2e-'))
const filePath = join(textEditTempDir, 'textedit-target.txt')
await writeFile(filePath, 'seed', 'utf8')
await execFileAsync('open', ['-a', 'TextEdit', '-n', filePath])
await delay(5500)
await execFileAsync('open', ['-F', '-a', 'TextEdit', '-n', filePath])
// Why: cold CI/user launches can register the process before System Events
// exposes its first window; short waits make the live computer-use proof flaky.
await waitForMacAppWindow('TextEdit', 15000)
}
export async function killTextEdit(): Promise<void> {
@@ -62,19 +46,119 @@ export async function killTextEdit(): Promise<void> {
}
}
export type SafariDraftFixture = {
title: string
}
export async function ensureSafariDraftFixtureLaunched(): Promise<SafariDraftFixture> {
await closeSafariDraftFixture()
safariDraftTempDir = await mkdtemp(join(tmpdir(), 'orca-computer-safari-e2e-'))
safariDraftTitle = `Orca Computer Use Draft Fixture ${Date.now()}`
const filePath = join(safariDraftTempDir, 'index.html')
await writeFile(filePath, safariDraftFixtureHtml(safariDraftTitle), 'utf8')
await execFileAsync('open', ['-F', '-a', 'Safari', filePath])
await waitForMacAppWindow('Safari', 15000)
await waitForComputerWindowTitle('com.apple.Safari', safariDraftTitle, 15000)
return { title: safariDraftTitle }
}
export async function closeSafariDraftFixture(): Promise<void> {
const title = safariDraftTitle
if (title) {
try {
const envelope = parseJsonOutput<{
result: {
windows: { id?: number | null; index: number; title: string }[]
}
}>(
(await runOrcaCli(['computer', 'list-windows', '--app', 'com.apple.Safari', '--json']))
.stdout
)
const target = envelope.result.windows.find((window) => window.title.includes(title))
if (target) {
const targetArgs =
target.id !== undefined && target.id !== null
? ['--window-id', String(target.id)]
: ['--window-index', String(target.index)]
await runOrcaCli([
'computer',
'hotkey',
'--app',
'com.apple.Safari',
...targetArgs,
'--key',
'CmdOrCtrl+W',
'--restore-window',
'--no-screenshot',
'--json'
])
}
} catch {
// The test-owned Safari tab may already be closed or the runtime may be gone.
}
safariDraftTitle = null
}
if (safariDraftTempDir) {
await rm(safariDraftTempDir, { force: true, recursive: true })
safariDraftTempDir = null
}
}
export async function activateFinder(): Promise<void> {
await execFileAsync('open', ['-a', 'Finder'])
await delay(1000)
}
async function waitForMacAppWindow(appName: string, timeoutMs: number): Promise<void> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
try {
const result = await execFileAsync('osascript', [
'-e',
`tell application "System Events" to tell process "${escapeAppleScript(appName)}" to count windows`
])
if (Number.parseInt(result.stdout.trim(), 10) > 0) {
return
}
} catch {
// The app process may not have registered with System Events yet.
}
await delay(250)
}
throw new Error(`${appName} did not expose a visible window within ${timeoutMs}ms`)
}
async function waitForComputerWindowTitle(
app: string,
title: string,
timeoutMs: number
): Promise<void> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
try {
const envelope = parseJsonOutput<{
result: { windows: { title: string }[] }
}>((await runOrcaCli(['computer', 'list-windows', '--app', app, '--json'])).stdout)
if (envelope.result.windows.some((window) => window.title.includes(title))) {
return
}
} catch {
// The browser window may not be visible to the provider yet.
}
await delay(250)
}
throw new Error(`${app} did not expose a window titled ${title} within ${timeoutMs}ms`)
}
export async function ensureGeditLaunched(): Promise<void> {
await killGedit()
linuxTempDir = await mkdtemp(join(tmpdir(), 'orca-computer-linux-e2e-'))
const filePath = join(linuxTempDir, 'gedit-target.txt')
const fileName = 'gedit-target.txt'
const filePath = join(linuxTempDir, fileName)
await writeFile(filePath, 'seed', 'utf8')
geditProcess = spawn('gedit', [filePath], { detached: true, stdio: 'ignore' })
geditProcess.unref()
await delay(3500)
await waitForComputerWindowTitle('gedit', fileName, 15000)
}
export async function killGedit(): Promise<void> {
@@ -141,10 +225,6 @@ export function findRoleIndex(treeText: string, role: string | RegExp): number {
return match?.[1] ? Number.parseInt(match[1], 10) : -1
}
export function parseJsonOutput<T>(stdout: string): T {
return JSON.parse(stdout) as T
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
@@ -184,6 +264,39 @@ function powerShellSingleQuoted(value: string): string {
return `'${value.replaceAll("'", "''")}'`
}
function escapeAppleScript(value: string): string {
return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')
}
function safariDraftFixtureHtml(title: string): string {
const escapedTitle = escapeHtml(title)
return [
'<!doctype html>',
'<html>',
'<head>',
`<title>${escapedTitle}</title>`,
'</head>',
'<body>',
'<main>',
'<h1>Draft Fixture</h1>',
'<label>Recipient <input id="recipient" aria-label="Recipient"></label>',
'<label>Body <textarea id="body" aria-label="Body"></textarea></label>',
"<button id=\"save\" onclick=\"document.getElementById('status').textContent = 'Draft ready: ' + document.getElementById('recipient').value + ' / ' + document.getElementById('body').value\">Save draft</button>",
'<p id="status" role="status">Draft empty</p>',
'</main>',
'</body>',
'</html>'
].join('\n')
}
function escapeHtml(value: string): string {
return value
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
}
function escapeRegExp(input: string): string {
return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
+3
View File
@@ -4,6 +4,9 @@ export default defineConfig({
test: {
environment: 'node',
include: ['tests/e2e/computer-*.e2e.ts'],
// Why: computer-use E2E files share the real desktop focus, clipboard, and
// app windows. Parallel files can steal focus from each other.
fileParallelism: false,
testTimeout: 60_000,
hookTimeout: 60_000
}