Files
claude-code-haha/scripts/quality-gate/computer-use-live-smoke.test.ts
T
程序员阿江(Relakkes) b8a90626ce feat(computer-use): native macOS engine, on top of main and nothing else
Rebuilt against main so the branch carries the Computer Use work and no other
divergence. Three unrelated efforts had been sitting uncommitted in this
worktree and were swept into an earlier commit; they are preserved on
cu-worktree-full-backup and belong on their own branches — adapter control
credentials, Electron asar sealing, and the sidecar code-loading audit. Every
file outside Computer Use now matches main exactly.

The engine
  A Swift helper drives apps through the accessibility tree, with coordinate
  actuation for the Chromium and Electron apps whose tree is a bare window
  frame. Ten primitives matching the shape Codex uses, so an app's guidance and
  the model's habits transfer.

  Coordinate actions resolve their target window once and refuse when none can
  be named. The unbound event they used to fall back to is discarded by custom
  renderers, so a minimized target produced a whole session of "Action
  completed" with nothing behind it.

  Input acceptance is established for typing and key presses as well as clicks:
  each MCP call is seconds apart, so the keyboard cannot inherit the focus a
  click established. The synthetic focus notification is gated on the target
  not already being active — sent unconditionally it names window 0 at an app
  that already owns a key window, and nine window-bound clicks were discarded
  with the traffic lights fully lit.

State the model can trust
  An off-screen target says so, and says which tools still reach it: element
  actions need no on-screen geometry, so an app with a real tree can still be
  driven from the Dock. A fully covered window is recovered once, then left
  alone — burying it again is the user wanting their screen back. A repeated
  capture is reported with the cause that actually applies rather than both,
  because coverage is something we compute.

Signing
  The helper is signed under a stable identity before electron-builder sees it,
  and excluded from re-signing: macOS ties Accessibility and Screen Recording
  grants to the signing identity, so rotating it drops both on every update.

Discoverability
  The desktop slash menu falls back to a directory scan while a session's CLI
  has not started, which is when the menu is first opened. Built-ins and
  bundled skills live in the binary, so /computer-use was absent until after
  the first message.
2026-08-05 22:06:23 +08:00

440 lines
13 KiB
TypeScript

import { describe, expect, test } from 'bun:test'
import {
assertChangedState,
assertCleanupEvidence,
assertMonitorContinuity,
assertPointerTrace,
assertNoChangeState,
assertSafeRunDirectory,
assertScreenshotChanged,
assertStaleHandleFailure,
assertSystemStatePreserved,
acquireLiveSmokeLock,
deriveLiveSmokePaths,
findEditableHandle,
hasExactNoChangeState,
hasFreshScreenshot,
errorMessage,
parseInputMonitorSnapshot,
parseLiveSmokeArgs,
parseSystemSnapshot,
type LiveAppState,
type SystemSnapshot,
} from './computer-use-live-smoke.js'
const initialSystemSnapshot: SystemSnapshot = {
frontmost: {
pid: 101,
bundleId: 'com.openai.codex',
executablePath: '/Applications/Codex.app/Contents/MacOS/Codex',
launchTime: 1234.5,
},
pointer: { x: 100, y: 200 },
input: {
flags: '0',
buttons: [false, false, false, false, false],
},
}
const PNG_ONE =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='
const PNG_TWO =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC'
function state(overrides: Partial<LiveAppState> = {}): LiveAppState {
return {
pid: 220,
bundleId: 'com.apple.TextEdit',
appName: 'TextEdit',
windowTitle: 'smoke-fixture.txt',
elementCount: 3,
truncated: false,
durationMs: 10,
axText: [
'g8:0 standard window smoke-fixture.txt',
'\tg8:7 text area CC_HAHA_SMOKE_STABLE_TOKEN',
'\tg8:9 button close',
].join('\n'),
elements: [
{
index: 7,
role: 'AXTextArea',
settable: true,
value: 'CC_HAHA_SMOKE_STABLE_TOKEN',
},
],
screenshot: {
base64: PNG_ONE,
width: 1,
height: 1,
},
...overrides,
}
}
describe('computer-use live smoke CLI safety', () => {
test('surfaces every primary and cleanup error from an AggregateError', () => {
expect(errorMessage(new AggregateError([
new Error('primary failed'),
new Error('cleanup failed'),
], 'smoke failed'))).toContain('primary failed')
expect(errorMessage(new AggregateError([
new Error('primary failed'),
new Error('cleanup failed'),
], 'smoke failed'))).toContain('cleanup failed')
})
test('defaults to the dedicated TextEdit target and accepts only its exact bundle id', () => {
expect(parseLiveSmokeArgs([])).toEqual({
targetBundleId: 'com.apple.TextEdit',
})
expect(parseLiveSmokeArgs(['--target', 'com.apple.TextEdit'])).toEqual({
targetBundleId: 'com.apple.TextEdit',
})
})
test('acquires/releases the production lock and performs no release when blocked', async () => {
let releases = 0
const release = await acquireLiveSmokeLock(
async () => ({ kind: 'acquired', fresh: true }),
async () => {
releases += 1
return true
},
)
expect(releases).toBe(0)
await release()
expect(releases).toBe(1)
let blockedRelease = 0
await expect(
acquireLiveSmokeLock(
async () => ({ kind: 'blocked', by: 'other-session' }),
async () => {
blockedRelease += 1
return true
},
),
).rejects.toThrow(/did not start/i)
expect(blockedRelease).toBe(0)
})
test('refuses Finder, terminal, system, and arbitrary targets', () => {
for (const target of [
'Finder',
'com.apple.finder',
'Terminal',
'com.apple.Terminal',
'System Settings',
'com.apple.systempreferences',
'com.googlecode.iterm2',
'com.example.OtherApp',
]) {
expect(() => parseLiveSmokeArgs(['--target', target])).toThrow(
/dedicated TextEdit/i,
)
}
})
test('rejects missing values and unknown CLI flags', () => {
expect(() => parseLiveSmokeArgs(['--target'])).toThrow(/value/i)
expect(() => parseLiveSmokeArgs(['--fixture', '/tmp/user-file.txt'])).toThrow(
/unknown argument/i,
)
})
})
describe('computer-use live smoke path confinement', () => {
test('derives the fixture and this process daemon artifacts deterministically', () => {
expect(
deriveLiveSmokePaths(
'/tmp/cc-haha-cu-live-smoke-ABC123',
'/Users/test/.claude/.runtime',
4321,
),
).toEqual({
runDirectory: '/tmp/cc-haha-cu-live-smoke-ABC123',
fixturePath:
'/tmp/cc-haha-cu-live-smoke-ABC123/computer-use-smoke-fixture.txt',
targetIdentityPath:
'/tmp/cc-haha-cu-live-smoke-ABC123/.textedit-identity.json',
daemonSocket:
'/Users/test/.claude/.runtime/cu-helper.daemon.4321.1.sock',
daemonPidfile:
'/Users/test/.claude/.runtime/cu-helper.daemon.4321.1.sock.pid',
})
})
test('accepts only one generated child directory directly beneath /tmp', () => {
expect(() =>
assertSafeRunDirectory('/tmp/cc-haha-cu-live-smoke-ABC123'),
).not.toThrow()
for (const unsafe of [
'/',
'/tmp',
'/tmp/cc-haha-cu-live-smoke-',
'/tmp/cc-haha-cu-live-smoke-ABC123/..',
'/var/tmp/cc-haha-cu-live-smoke-ABC123',
'/tmp/other-ABC123',
]) {
expect(() => assertSafeRunDirectory(unsafe)).toThrow(/unsafe/i)
}
})
})
describe('computer-use live smoke state evidence', () => {
test('parses a complete system snapshot and rejects unproven foreground identity', () => {
expect(parseSystemSnapshot(JSON.stringify(initialSystemSnapshot))).toEqual(
initialSystemSnapshot,
)
expect(() =>
parseSystemSnapshot(
JSON.stringify({
...initialSystemSnapshot,
frontmost: { ...initialSystemSnapshot.frontmost, launchTime: null },
}),
),
).toThrow(/frontmost/i)
})
test('accepts at most one pixel of pointer drift with exact foreground and held-input state', () => {
expect(() =>
assertSystemStatePreserved(initialSystemSnapshot, {
...initialSystemSnapshot,
pointer: { x: 100.6, y: 200.6 },
}),
).not.toThrow()
expect(() =>
assertSystemStatePreserved(initialSystemSnapshot, {
...initialSystemSnapshot,
pointer: { x: 101.01, y: 200 },
}),
).toThrow(/pointer drift/i)
})
test('rejects PID reuse, foreground replacement, and stuck input state', () => {
expect(() =>
assertSystemStatePreserved(initialSystemSnapshot, {
...initialSystemSnapshot,
frontmost: { ...initialSystemSnapshot.frontmost, launchTime: 9999 },
}),
).toThrow(/frontmost identity/i)
expect(() =>
assertSystemStatePreserved(initialSystemSnapshot, {
...initialSystemSnapshot,
input: {
...initialSystemSnapshot.input,
buttons: [true, false, false, false, false],
},
}),
).toThrow(/held input/i)
})
test('rejects transient pointer movement even if the endpoint was restored', () => {
expect(() => assertPointerTrace({ samples: 50, maxDriftPx: 0.8 })).not.toThrow()
expect(() => assertPointerTrace({ samples: 50, maxDriftPx: 12 })).toThrow(
/transiently/i,
)
expect(() => assertPointerTrace({ samples: 1, maxDriftPx: 0 })).toThrow(
/too few samples/i,
)
})
test('requires an available, continuous physical-input monitor', () => {
const before = parseInputMonitorSnapshot({
epoch: '42',
available: true,
continuityGeneration: '3',
})
const after = parseInputMonitorSnapshot({
epoch: '42',
available: true,
continuityGeneration: '3',
})
expect(() => assertMonitorContinuity(before, after)).not.toThrow()
expect(() =>
parseInputMonitorSnapshot({
epoch: '42',
available: false,
continuityGeneration: '3',
}),
).toThrow(/physical-input monitor/i)
expect(() =>
assertMonitorContinuity(before, { ...after, epoch: 43n }),
).toThrow(/physical input/i)
expect(() =>
assertMonitorContinuity(before, {
...after,
continuityGeneration: 4n,
}),
).toThrow(/continuity/i)
})
})
describe('computer-use live smoke AX proof', () => {
test('wait predicates reject transiently missing captures', () => {
expect(hasFreshScreenshot(state())).toBe(true)
expect(hasFreshScreenshot(state({ screenshot: undefined }))).toBe(false)
expect(hasFreshScreenshot(state({
screenshot: { base64: 'not-a-png', width: 1, height: 1 },
}))).toBe(false)
})
test('derives an opaque editable handle from raw element metadata plus rendered generation', () => {
expect(findEditableHandle(state(), 'CC_HAHA_SMOKE_STABLE_TOKEN')).toBe(
'g8:7',
)
})
test('rejects ambiguous or non-settable editable elements', () => {
expect(() =>
findEditableHandle(
state({
elements: [
{
index: 7,
role: 'AXTextArea',
settable: false,
value: 'CC_HAHA_SMOKE_STABLE_TOKEN',
},
],
}),
'CC_HAHA_SMOKE_STABLE_TOKEN',
),
).toThrow(/exactly one/i)
expect(() =>
findEditableHandle(
state({
elements: [
{
index: 7,
role: 'AXTextArea',
settable: true,
value: 'CC_HAHA_SMOKE_STABLE_TOKEN',
},
{
index: 8,
role: 'AXTextField',
settable: true,
value: 'CC_HAHA_SMOKE_STABLE_TOKEN',
},
],
axText:
'g8:7 text area CC_HAHA_SMOKE_STABLE_TOKEN\ng8:8 text field CC_HAHA_SMOKE_STABLE_TOKEN',
}),
'CC_HAHA_SMOKE_STABLE_TOKEN',
),
).toThrow(/exactly one/i)
})
test('requires the exact no-change header and a changed diff with a real screenshot', () => {
expect(hasExactNoChangeState(state({
axText:
'There has been no change in the accessibility tree for Window: "smoke-fixture.txt".',
}))).toBe(true)
expect(hasExactNoChangeState(state({
axText:
'The following is a diff from the previous accessibility tree for Window: "smoke-fixture.txt".',
}))).toBe(false)
expect(() =>
assertNoChangeState(
state({
axText:
'There has been no change in the accessibility tree for Window: "smoke-fixture.txt".',
}),
),
).not.toThrow()
expect(() =>
assertNoChangeState(state({ axText: 'g8:0 standard window' })),
).toThrow(/no-change/i)
expect(() =>
assertChangedState(
state({
axText:
'The following is a diff from the previous accessibility tree for Window: "smoke-fixture.txt" with ~ and + representing changed and added elements, respectively. Removed elements are summarized by ID range.\n~\tg8:7 text area MUTATED',
}),
'MUTATED',
),
).not.toThrow()
expect(() =>
assertChangedState(
state({
axText:
'The following is a diff from the previous accessibility tree for Window: "smoke-fixture.txt" with ~ and + representing changed and added elements, respectively. Removed elements are summarized by ID range.\n~\tg8:7 text area MUTATED',
screenshot: { base64: '', width: 0, height: 0 },
}),
'MUTATED',
),
).toThrow(/screenshot/i)
})
test('rejects fake PNG text and reused mutation screenshots', () => {
expect(() =>
assertNoChangeState(
state({
axText:
'There has been no change in the accessibility tree for Window: "smoke-fixture.txt".',
screenshot: { base64: 'a'.repeat(128), width: 1, height: 1 },
}),
),
).toThrow(/PNG|screenshot/i)
expect(() => assertScreenshotChanged(state(), state())).toThrow(/reused/i)
expect(() =>
assertScreenshotChanged(
state(),
state({ screenshot: { base64: PNG_TWO, width: 1, height: 1 } }),
),
).not.toThrow()
})
test('accepts only an authoritative stale-handle failure', () => {
expect(() =>
assertStaleHandleFailure(
new Error(
'Snapshot handle g9:4 is stale. Re-query the latest state with get_app_state before sending more actions.',
),
),
).not.toThrow()
expect(() =>
assertStaleHandleFailure(new Error('Accessibility permission is required')),
).toThrow(/not a stale-handle/i)
})
})
describe('computer-use live smoke cleanup proof', () => {
test('requires socket, pidfile, owned daemon, and held input to be gone', () => {
expect(() =>
assertCleanupEvidence({
daemonSocketExists: false,
daemonPidfileExists: false,
daemonProcessStillMatches: false,
inputBefore: initialSystemSnapshot.input,
inputAfter: initialSystemSnapshot.input,
}),
).not.toThrow()
expect(() =>
assertCleanupEvidence({
daemonSocketExists: true,
daemonPidfileExists: false,
daemonProcessStillMatches: false,
inputBefore: initialSystemSnapshot.input,
inputAfter: initialSystemSnapshot.input,
}),
).toThrow(/socket/i)
})
})