test: remove 181 low-value mobile, CI and runtime tests (#39351)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-06 23:39:35 -08:00
committed by GitHub
co-authored by OrcaWin
parent d3a24e358b
commit ff416c2f6c
55 changed files with 15 additions and 4610 deletions
@@ -1,15 +1,7 @@
import { EventEmitter } from 'node:events'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { PostgresDatabase } from './database.js'
import type pg from 'pg'
import {
noteConnectionStatement,
SLOW_CONNECTION_PEER_SLACK_MS,
SLOW_CONNECTION_RETIRE_INTERVAL_MS,
SLOW_CONNECTION_SAMPLE_MAX_AGE_MS,
SLOW_CONNECTION_WINDOW,
SlowConnectionRetirement
} from './postgres-connection-latency.js'
import { SLOW_CONNECTION_RETIRE_INTERVAL_MS, SLOW_CONNECTION_SAMPLE_MAX_AGE_MS, SLOW_CONNECTION_WINDOW } from './postgres-connection-latency.js'
let clock = 0
@@ -100,13 +92,6 @@ describe('slow connection retirement', () => {
])
})
it('retires nothing in a pool whose round-trip floor is high, as in a far region', async () => {
const far = pool(['a', 'b', 'c'].map((name) => ({ name, statementMs: steady(180) })))
await runStatements(far.database, SLOW_CONNECTION_WINDOW * 6)
expect(far.destroyed).toEqual([])
})
it('retires nothing when the whole database slows down', async () => {
let slowDatabase = false
const statementMs = () => (slowDatabase ? 60 : 3)
@@ -183,38 +168,6 @@ describe('slow connection retirement', () => {
expect(two.destroyed).toEqual(['slow-1', 'slow-2'])
})
it('bounds the misfire at a database-wide slowdown onset while peers sit idle', () => {
const retirement = new SlowConnectionRetirement(() => clock)
const peers = [fakeClient(), fakeClient()]
for (const peer of peers) {
for (let index = 0; index < 8; index++) {
retirement.track(peer)
noteConnectionStatement(peer, 3)
retirement.shouldRetire(peer, 1)
}
}
// From here every statement is slow, and only the busy connection (and its redials) runs.
let busy = fakeClient()
let id = 10
const retiredAt: number[] = []
for (let elapsed = 0; elapsed < 120_000; elapsed += 60) {
clock += 60
retirement.track(busy)
noteConnectionStatement(busy, 60)
if (retirement.shouldRetire(busy, id)) {
retiredAt.push(elapsed)
busy = fakeClient()
id++
}
}
expect(retiredAt.length).toBeLessThanOrEqual(3)
expect(retiredAt.length).toBeGreaterThan(0)
expect(Math.max(...retiredAt)).toBeLessThan(
SLOW_CONNECTION_PEER_SLACK_MS + SLOW_CONNECTION_RETIRE_INTERVAL_MS
)
})
// Every 50th statement takes `outlierMs`: a 2% tail, like the ~200/400/800 ms retransmit stalls.
const withTail = (baseMs: number, outlierMs: number) => {
let calls = 0
@@ -237,31 +190,6 @@ describe('slow connection retirement', () => {
})
})
it('retires nothing when every connection has the same tail, as a whole-database spike does', async () => {
const spiky = pool(['a', 'b', 'c'].map((name) => ({ name, statementMs: withTail(3, 400) })))
await runStatements(spiky.database, 900)
expect(spiky.destroyed).toEqual([])
})
it('retires nothing on a far region whose healthy tail sits above 200 ms', async () => {
const far = pool(['a', 'b', 'c'].map((name) => ({ name, statementMs: withTail(180, 260) })))
await runStatements(far.database, 900)
expect(far.destroyed).toEqual([])
})
it('lets one peer with a slow statement of its own block a tail retirement', async () => {
const noisy = pool([
{ name: 'a', statementMs: steady(3) },
{ name: 'noisy', statementMs: withTail(3, 90) },
{ name: 'lossy', statementMs: withTail(3, 415) }
])
await runStatements(noisy.database, 900)
expect(noisy.destroyed).toEqual([])
})
it('never retires, or records, on a pool built without retirement, as cells are', async () => {
const cell = pool(
[
@@ -278,26 +206,4 @@ describe('slow connection retirement', () => {
expect(warnings).toEqual([])
})
it('drops clients the pool closed on idle, even when nothing else is judged', () => {
const retirement = new SlowConnectionRetirement(() => clock)
for (let id = 1; id <= 50; id++) {
const closedLater = fakeClient()
retirement.track(closedLater)
noteConnectionStatement(closedLater, 3)
retirement.shouldRetire(closedLater, id)
}
expect(retirement.trackedClients).toBe(50)
clock += SLOW_CONNECTION_SAMPLE_MAX_AGE_MS + 1
const live = fakeClient()
retirement.track(live)
noteConnectionStatement(live, 3)
retirement.shouldRetire(live, 51)
expect(retirement.trackedClients).toBe(1)
})
})
function fakeClient(): pg.PoolClient {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the retirement rule only uses clients as identity keys.
return {} as pg.PoolClient
}
@@ -1,120 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
CONTROL_RTT_RESERVOIR_LIMIT,
PRE_AUTH_RESERVOIR_LIMIT,
RelayObservability,
STICKY_CONNECTION_LIMIT,
type RelayProcessCounts
} from './relay-observability.js'
const counts: RelayProcessCounts = {
totalConnections: 9,
preAuthConnections: 1,
controls: 2,
splices: 3,
pendingSplices: 1,
queuedBytes: 4096,
databasePoolTotal: 3,
databasePoolIdle: 0,
databasePoolWaiting: 2,
databasePoolWaitersMax: 3,
databasePoolOldestWaitMs: 750,
databasePoolWaitMsMax: 1_250
}
describe('relay observability', () => {
afterEach(() => vi.restoreAllMocks())
// Why: a director whose loop froze for 134 s still reported a 68 ms p99 (staging 2026-10-11).
it('reports one long event-loop freeze as the window max', async () => {
const entries: Array<Record<string, unknown>> = []
const observability = new RelayObservability(
{ role: 'director', cellId: 'director', region: 'us-central1' },
(entry) => entries.push(entry)
)
observability.start(() => counts, 3_600_000)
await new Promise((resolve) => setTimeout(resolve, 100))
const frozenUntil = performance.now() + 300
while (performance.now() < frozenUntil) {
// Holds the loop the way a blocking connect() does.
}
await new Promise((resolve) => setTimeout(resolve, 100))
observability.flush(counts)
observability.stop()
expect(entries[0]!.eventLoopDelayMsMax).toBeGreaterThanOrEqual(250)
})
it('bounds the per-connection sticky summary', () => {
const entries: Array<Record<string, unknown>> = []
const observability = new RelayObservability(
{ role: 'director', cellId: 'director', region: 'us-central1' },
(entry) => entries.push(entry)
)
for (let id = 1; id <= STICKY_CONNECTION_LIMIT + 3; id++) {
observability.recordStickySlot({
queueWaitMs: 0,
poolWaitMs: 0,
sqlMs: 1,
statements: 1,
statementMsByConnection: new Map([[id, [1]]])
})
}
observability.flush(counts)
expect(Object.keys(entries[0]?.stickySqlByConnection as object)).toHaveLength(
STICKY_CONNECTION_LIMIT
)
expect(entries[0]).toMatchObject({ stickySqlConnectionSamplesDroppedDelta: 3 })
})
it('samples the whole flooded window rather than its first samples', () => {
let seed = 42
vi.spyOn(Math, 'random').mockImplementation(() => {
seed = (Math.imul(seed, 1_664_525) + 1_013_904_223) >>> 0
return seed / 0x1_0000_0000
})
const entries: Array<Record<string, unknown>> = []
const observability = new RelayObservability(
{ role: 'cell', cellId: 'production-gce-c28', region: 'asia-east2' },
(entry) => entries.push(entry)
)
const half = CONTROL_RTT_RESERVOIR_LIMIT * 10
for (let sample = 0; sample < half; sample++) observability.recordControlRtt(10)
for (let sample = 0; sample < half; sample++) observability.recordControlRtt(900)
observability.flush(counts)
// A first-N reservoir would publish only the early 10 ms samples.
expect(entries[0]!.controlRttMsP95).toBe(900)
expect(entries[0]!.controlRttMsMax).toBe(900)
})
it('counts every hello in the pre-auth buckets, inclusive of each bound', () => {
const entries: Array<Record<string, unknown>> = []
const observability = new RelayObservability(
{ role: 'cell', cellId: 'staging-gce-c1', region: 'us-central1' },
(entry) => entries.push(entry)
)
const flooded = PRE_AUTH_RESERVOIR_LIMIT * 5
for (let sample = 0; sample < flooded; sample++) {
observability.recordHostPreAuth('reserve', 'admitted', 450)
}
observability.recordHostPreAuth('reserve', 'admitted', 450.001)
observability.recordHostPreAuth('reserve', 'admitted', 9_000)
observability.flush(counts)
expect(entries[0]).toMatchObject({
preAuthLatencyMs: {
reserve: {
admitted: {
// Exact past the reservoir cap, even when it declined the slowest hello.
count: flooded + 2,
max: 9_000,
p50: 450,
bucketsLeMs: { '300': 0, '450': flooded, '700': 1, '5000': 0, '+Inf': 1 }
}
}
}
})
})
})
@@ -1,44 +0,0 @@
import { describe, expect, it } from 'vitest'
import { parseProcNetSnmpTcp, sandboxTcpCounterDeltas } from './sandbox-tcp-counters.js'
// Tcp lines in /proc/net/snmp's layout, with counter values a Cloud Run gen1 (gVisor) sandbox reported on 2026-10-26.
const GEN1_SNMP = [
'Ip: Forwarding DefaultTTL InReceives',
'Ip: 1 64 2000',
'Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts InCsumErrors',
'Tcp: 1 200 120000 -1 5 3 0 0 2 485 212 1 0 122 0',
'Udp: InDatagrams NoPorts',
'Udp: 4 0'
].join('\n')
const counters = (retransSegs: number, inSegs = 485) => ({
inSegs,
outSegs: 212,
retransSegs,
inErrs: 0,
outRsts: 122,
estabResets: 0
})
describe('sandbox TCP counters', () => {
it('reads the Tcp counters of /proc/net/snmp', () => {
expect(parseProcNetSnmpTcp(GEN1_SNMP)).toEqual(counters(1))
})
it('reads nothing from a file without both Tcp lines or with a non-numeric counter', () => {
expect(parseProcNetSnmpTcp('Ip: Forwarding\nIp: 1')).toBeUndefined()
expect(parseProcNetSnmpTcp(GEN1_SNMP.replace(' 485 ', ' x '))).toBeUndefined()
})
it('reports per-window deltas, and none across a counter reset', () => {
expect(sandboxTcpCounterDeltas(counters(1), counters(4, 900))).toEqual({
tcpInSegsDelta: 415,
tcpOutSegsDelta: 0,
tcpRetransSegsDelta: 3,
tcpInErrsDelta: 0,
tcpOutRstsDelta: 0,
tcpEstabResetsDelta: 0
})
expect(sandboxTcpCounterDeltas(counters(4), counters(1))).toBeUndefined()
})
})
+1 -3
View File
@@ -15978,13 +15978,11 @@
"commands": [
"gh workflow run windows-wsl-e2e.yml",
"pnpm exec playwright test tests/e2e/golden-tab-bar-agent-launch.spec.ts tests/e2e/terminal-windows-shell-paste-ownership.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1",
"node_modules/.bin/vitest run --config config/vitest.config.ts config/scripts/workflow/source-routing/wsl-e2e-lane-contract.test.mjs",
"gh run view 34031806291 --log"
],
"testFiles": [
"tests/e2e/golden-tab-bar-agent-launch.spec.ts",
"tests/e2e/terminal-windows-shell-paste-ownership.spec.ts",
"config/scripts/workflow/source-routing/wsl-e2e-lane-contract.test.mjs"
"tests/e2e/terminal-windows-shell-paste-ownership.spec.ts"
],
"assertionRefs": [
{
@@ -1,147 +0,0 @@
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { runInNewContext } from 'node:vm'
import { parse } from 'yaml'
import { describe, expect, it } from 'vitest'
import { runProcessSync } from '@orca/process-host'
const action = parse(readFileSync('.github/actions/install-node-dependencies/action.yml', 'utf8'))
const mode = action.runs.steps.find((step) => step.id === 'pnpm-store-mode')
const defaultContext = {
github: { event_name: 'push' },
runner: { os: 'Linux', arch: 'X64', environment: 'github-hosted' },
job: { container: { id: '' } },
inputs: {
'cache-pnpm-store': 'true',
'cache-pnpm-store-lookup-only': 'auto',
'cache-dependency-path': 'pnpm-lock.yaml',
'node-version': ''
}
}
const expression = mode.if.replaceAll(/inputs\.([\w-]+)/g, 'inputs["$1"]')
function eligible(changes) {
const context = structuredClone(defaultContext)
for (const [name, fields] of Object.entries(changes)) {
Object.assign(context[name], fields)
}
return runInNewContext(expression, context)
}
function resolveMode(request, node, manager) {
const directory = mkdtempSync(join(tmpdir(), 'orca-store-mode-'))
const output = join(directory, 'output')
try {
writeFileSync(
join(directory, 'package.json'),
JSON.stringify({ engines: { node }, packageManager: manager })
)
const result = runProcessSync({
program: 'bash',
args: ['-e', '-o', 'pipefail', '-c', mode.run],
cwd: directory,
env: { ...process.env, LOOKUP_REQUEST: request, GITHUB_OUTPUT: output }
})
expect(result.code, result.stderr || result.stdout).toBe(0)
return readFileSync(output, 'utf8')
} finally {
rmSync(directory, { recursive: true, force: true })
}
}
describe('automatic pnpm store mode', () => {
it.each([
['auto', '24', 'pnpm@12.14.0', '', true],
['auto', '25', 'pnpm@12.14.0', 'pnpm', false],
['auto', '24', 'pnpm@13.0.0', 'pnpm', false],
['true', '25', 'pnpm@13.0.0', '', true]
])(
'routes resolved %s mode for Node %s / %s into both cache steps',
(request, node, manager, cache, lookup) => {
const context = structuredClone(defaultContext)
context.inputs['cache-pnpm-store-lookup-only'] = request
const output = resolveMode(request, node, manager)
expect(output).toBe(`lookup-only=${lookup}\n`)
const resolved = output.split('=')[1].trim()
const evaluate = (value) =>
runInNewContext(
value
.replaceAll(/inputs\.([\w-]+)/g, 'inputs["$1"]')
.replaceAll(
'steps.pnpm-store-mode.outputs.lookup-only',
'steps["pnpm-store-mode"].outputs["lookup-only"]'
),
{ ...context, steps: { 'pnpm-store-mode': { outputs: { 'lookup-only': resolved } } } }
)
const nodeSetup = action.runs.steps.find((step) => step.id === 'default-node')
expect(evaluate(nodeSetup.with.cache.slice(3, -2))).toBe(cache)
const publish = action.runs.steps.find((step) => step.id === 'pnpm-store-lookup').if
expect(evaluate(publish)).toBe(false)
context.runner.environment = 'self-hosted'
expect(evaluate(publish)).toBe(lookup)
}
)
it.each(
['Linux', 'Windows', 'macOS'].flatMap((os) => ['X64', 'ARM64'].map((arch) => [os, arch]))
)('qualifies the measured %s/%s hosted root context', (os, arch) => {
expect(eligible({ runner: { os, arch } })).toBe(true)
})
it.each([
['PR', { github: { event_name: 'pull_request' } }],
['opted-out store', { inputs: { 'cache-pnpm-store': 'false' } }],
['opted-out lookup', { inputs: { 'cache-pnpm-store-lookup-only': 'false' } }],
['unknown request', { inputs: { 'cache-pnpm-store-lookup-only': 'other' } }],
[
'mixed lockfiles',
{ inputs: { 'cache-dependency-path': 'pnpm-lock.yaml\nmobile/pnpm-lock.yaml' } }
],
['custom lockfile', { inputs: { 'cache-dependency-path': 'cloud/pnpm-lock.yaml' } }],
['Node 25', { inputs: { 'node-version': '25' } }],
['job container', { job: { container: { id: 'container-id' } } }],
['self-hosted runner', { runner: { environment: 'self-hosted' } }],
['unknown host kind', { runner: { environment: '' } }],
['unmeasured architecture', { runner: { arch: 'X86' } }],
['unmeasured OS', { runner: { os: 'other' } }]
])('retains the legacy policy for %s', (_name, changes) => {
expect(eligible(changes)).toBe(false)
})
it('allows an explicit request to preserve the existing force-lookup contract', () => {
expect(
eligible({
inputs: {
'cache-pnpm-store-lookup-only': 'true',
'node-version': '25',
'cache-dependency-path': 'custom-lock.yaml'
},
runner: { environment: 'self-hosted' },
job: { container: { id: 'container-id' } }
})
).toBe(true)
expect(
eligible({
github: { event_name: 'pull_request' },
inputs: { 'cache-pnpm-store-lookup-only': 'true' }
})
).toBe(false)
})
it.each([
['24', 'pnpm@12.14.0+sha512.fixture', 'true'],
['24.x', 'pnpm@12.14.0', 'false'],
['24', 'pnpm@12.8.2', 'false'],
['24', 'pnpm@12.14.00', 'false'],
['24', undefined, 'false'],
[undefined, 'pnpm@12.14.0', 'false'],
['24', 12, 'false']
])('checks manifest Node %s and manager %s before choosing lookup', (node, manager, expected) => {
expect(resolveMode('auto', node, manager)).toBe(`lookup-only=${expected}\n`)
})
it('checks uppercase auto requests consistently with GitHub expression comparisons', () => {
expect(resolveMode('AUTO', '25', 'pnpm@12.14.0')).toBe('lookup-only=false\n')
})
})
@@ -15,7 +15,6 @@
"timings": {
"config/scripts/release/workflow-contracts/adhoc-build-pinned-commit.test.mjs": 375,
"config/scripts/desktop-distribution/macos/adhoc-mac-manifests.test.mjs": 112,
"config/scripts/release/workflow-contracts/adhoc-release-waits.test.mjs": 151,
"config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs": 339,
"config/scripts/desktop-distribution/linux/appimage-node-runtime.test.mjs": 146,
"config/scripts/performance/measurement/benchmark-artifact-comparison.test.mjs": 192,
@@ -25,7 +24,6 @@
"config/scripts/desktop-distribution/macos/build-mac-notarization-overlap.test.mjs": 127,
"config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs": 202,
"config/scripts/native-build/composition/build-native-for-platform.test.mjs": 61,
"config/scripts/plugin-build/declarative-runtime/build-plugin-declarative-runtime.test.mjs": 259,
"config/scripts/native-build/linux/build-wayland-clipboard.test.mjs": 435,
"config/scripts/native-build/windows/build-windows-cli-launcher.test.mjs": 146,
"config/scripts/native-build/windows/build-windows-security-addon.test.mjs": 189,
@@ -52,7 +50,6 @@
"config/scripts/ci/e2e-selection/ci-e2e-shard-selection.test.mjs": 2772,
"config/scripts/ci/workflow-contracts/ci-managed-ssh-execution.test.mjs": 844,
"config/scripts/ci/workflow-contracts/ci-native-toolchain.test.mjs": 109,
"config/scripts/ci/dependency-cache/ci-pnpm-store-mode.test.mjs": 501,
"config/scripts/ci/sharding/ci-shard-assignment.test.mjs": 1381,
"config/scripts/ci/unit-selection/dependency-graph/ci-unit-dependency-graph.test.mjs": 413,
"config/scripts/ci/unit-selection/dependency-graph/ci-unit-exclusion-coverage.test.mjs": 1195,
@@ -93,7 +90,6 @@
"config/scripts/workspace-package-build/generated-artifact-line-ending-pin.test.mjs": 61,
"config/scripts/diagnostics/hang-watchdog/hang-watchdog-process-metrics.test.mjs": 94,
"config/scripts/runtime-verification/headless-detector/headless-detector-compiler-cache.test.mjs": 959,
"config/scripts/runtime-verification/daemon-lifecycle/headless-serve-shutdown-matrix.test.mjs": 100,
"config/scripts/ci/workflow-contracts/hourly-preflight-workflow.test.mjs": 158,
"config/scripts/performance/idle-cpu/idle-cpu-process-sampling.test.mjs": 55,
"config/scripts/static-analysis/oxlint-contracts/ime-enter-guard-plugin.test.mjs": 222,
@@ -113,7 +109,6 @@
"config/scripts/locale-catalog/locale-translation-policy.test.mjs": 189,
"config/scripts/localization/source-extraction/localization-extraction-call-syntax.test.mjs": 317,
"config/scripts/localization/extraction-policy/localization-extraction-change-scope.test.mjs": 732,
"config/scripts/desktop-distribution/macos/mac-notarization-builder-contract.test.mjs": 768,
"config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.test.mjs": 52,
"config/scripts/desktop-distribution/macos/macos-folder-usage-descriptions.test.mjs": 147,
"config/scripts/desktop-distribution/macos/macos-shipit-scheduling.test.mjs": 38,
@@ -207,11 +202,7 @@
"config/scripts/ci/e2e-selection/playwright-focused-workflow-selection.test.mjs": 1565,
"config/scripts/tool-invocation/pnpm-cli-invocation.test.mjs": 65,
"config/scripts/ci/workflow-contracts/pr-auxiliary-preflight-admission.test.mjs": 2174,
"config/scripts/workflow/source-routing/pr-code-change-scope-cross-version-launch-route.test.mjs": 54,
"config/scripts/workflow/source-routing/pr-code-change-scope-cross-version-send-path.test.mjs": 71,
"config/scripts/workflow/source-routing/pr-code-change-scope.test.mjs": 403,
"config/scripts/workflow/source-routing/pr-codex-unit-only-selection.test.mjs": 53,
"config/scripts/workflow/source-routing/pr-e2e-gate-contract.test.mjs": 270,
"config/scripts/ci/e2e-selection/pr-e2e-managed-ssh-harness-route.test.mjs": 422,
"config/scripts/ci/e2e-selection/pr-plugin-e2e-routing.test.mjs": 272,
"config/scripts/workflow/pr-admission/pr-ready-check-gate.test.mjs": 1343,
@@ -239,7 +230,6 @@
"config/scripts/worktree-storage/reclaim-vitest-module-caches.test.mjs": 109,
"config/scripts/worktree-storage/reclaim-worktree-generated-files.test.mjs": 3376,
"config/scripts/worktree-storage/reclaim-worktree-space.test.mjs": 2469,
"config/scripts/release/workflow-contracts/release-cut-token-permissions.test.mjs": 276,
"config/scripts/release/javascript-artifacts/release-javascript-artifact.test.mjs": 341,
"config/scripts/release/javascript-artifacts/release-javascript-parity.test.mjs": 88,
"config/scripts/release/workflow-contracts/release-mac-build-workflow-dispatch.test.mjs": 112,
@@ -304,7 +294,6 @@
"config/scripts/ci/workflow-contracts/workflow-ref-mirror-case-safety.test.mjs": 447,
"config/scripts/ci/workflow-contracts/workflow-ref-reachability.test.mjs": 1650,
"config/scripts/workspace/source-exports/workspace-source-exports.test.mjs": 117,
"config/scripts/workflow/source-routing/wsl-e2e-lane-contract.test.mjs": 235,
"config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-admission.test.mjs": 1430,
"config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-coordinate-boundaries.test.mjs": 191,
"config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-file-transport.test.mjs": 404,
@@ -8798,7 +8787,6 @@
"src/shared/ai-vault/scanning/ai-vault-scope-paths.test.ts": 73,
"src/shared/ai-vault/search/ai-vault-search-agent-history.test.ts": 168,
"src/shared/ai-vault/search/ai-vault-search-contract.test.ts": 148,
"src/shared/ai-vault/search/ai-vault-search-scope-contract.test.ts": 130,
"src/shared/ai-vault/search/ai-vault-search-status-fallback.test.ts": 175,
"src/shared/ai-vault/scanning/ai-vault-session-depth.test.ts": 78,
"src/shared/ai-vault/session-display/ai-vault-session-filters.test.ts": 176,
@@ -9543,7 +9531,6 @@
"src/shared/workspace-setup/setup-script-telemetry.test.ts": 44,
"src/shared/sha256.test.ts": 55,
"src/shared/shell-foreground-snapshot.test.ts": 272,
"src/shared/agent-status/process/shell-process-detection.test.ts": 47,
"src/shared/terminal/pty/native-process/shell-process-readiness.test.ts": 89,
"src/shared/sidebar-feed-client/sidebar-feed-reader.test.ts": 438,
"src/shared/sidebar-feed-client/sidebar-feed-snapshot.test.ts": 488,
@@ -1,13 +1,9 @@
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { importUnitTimingReports, importUnitTimingRuns } from './ci-unit-timing-import.mjs'
import UnitTimingReporter, {
buildUnitPhaseReport,
moduleDuration,
UNIT_PHASE_FILE_LIMIT
} from './ci-unit-timing-reporter.mjs'
import { importUnitTimingReports } from './ci-unit-timing-import.mjs'
import UnitTimingReporter, { buildUnitPhaseReport } from './ci-unit-timing-reporter.mjs'
const report = (index, timings) => ({
metric: 'module-duration-v1',
@@ -22,105 +18,6 @@ const report = (index, timings) => ({
})
describe('unit worker timing evidence', () => {
it('counts each worker phase once, including imports of tests with cheap assertions', () => {
expect(
moduleDuration({
environmentSetupDuration: 11,
prepareDuration: 12,
collectDuration: 130,
setupDuration: 14,
duration: 0.2,
importDurations: { dependency: 100 }
})
).toBe(168)
})
it.each([undefined, '24.21.0', '26.6.0'])(
'writes reporter provenance for selected Node version %s',
(nodeVersion) => {
const directory = mkdtempSync(join(tmpdir(), 'orca-unit-timing-'))
const previous = process.env.ORCA_UNIT_TIMING_REPORT
process.env.ORCA_UNIT_TIMING_REPORT = join(directory, 'unit-timings.json')
vi.stubEnv('ORCA_TEST_NODE_VERSION', nodeVersion)
vi.stubEnv('ORCA_UNIT_PHASE_REPORT', undefined)
try {
const reporter = new UnitTimingReporter()
reporter.onInit({ config: { root: process.cwd(), shard: { index: 1, count: 8 } } })
reporter.onTestRunEnd(
[
{
moduleId: resolve('src/example.test.ts'),
diagnostic: () => ({
environmentSetupDuration: 0,
prepareDuration: 0,
collectDuration: 200,
setupDuration: 10,
duration: 5
})
}
],
[],
'passed'
)
expect(JSON.parse(readFileSync(process.env.ORCA_UNIT_TIMING_REPORT, 'utf8'))).toMatchObject(
{
metric: 'module-duration-v1',
nodeVersion: nodeVersion ?? process.versions.node,
...(process.versions.bun ? { bunVersion: process.versions.bun } : {}),
shard: { index: 1, count: 8 },
status: 'passed',
unhandledErrors: 0,
timings: { 'src/example.test.ts': 215 }
}
)
} finally {
vi.unstubAllEnvs()
if (previous === undefined) {
delete process.env.ORCA_UNIT_TIMING_REPORT
} else {
process.env.ORCA_UNIT_TIMING_REPORT = previous
}
rmSync(directory, { recursive: true, force: true })
}
}
)
it('imports all shards without adding the old average overhead again', () => {
expect(importUnitTimingReports([report(2, { b: 100 }), report(1, { a: 200 })])).toMatchObject({
sourceSha: 'source',
overheadMs: 0,
metric: 'module-duration-v1',
timings: { a: 200, b: 100 }
})
})
it('averages each file over several complete runs and rejects repeated or mixed runs', () => {
const run = (runId, a, b) => [
{ ...report(1, { a }), runId },
{ ...report(2, { b }), runId }
]
expect(importUnitTimingRuns([run('r1', 100, 300), run('r2', 200, 500)])).toMatchObject({
runIds: ['r1', 'r2'],
overheadMs: 0,
timings: { a: 150, b: 400 }
})
expect(() => importUnitTimingRuns([run('r1', 100, 300), run('r1', 100, 300)])).toThrow(
'distinct'
)
const otherNode = run('r2', 200, 500).map((entry) => ({ ...entry, nodeVersion: '26.6.0' }))
expect(() => importUnitTimingRuns([run('r1', 100, 300), otherNode])).toThrow('distinct')
})
it('preserves Bun provenance and rejects mixing Bun and Node timing sets', () => {
const first = { ...report(1, { a: 100 }), bunVersion: '1.4.2' }
const second = { ...report(2, { b: 200 }), bunVersion: '1.4.2' }
expect(importUnitTimingReports([first, second])).toMatchObject({ bunVersion: '1.4.2' })
expect(() => importUnitTimingReports([first, report(2, { b: 200 })])).toThrow('successful')
expect(() => importUnitTimingReports([first, { ...second, bunVersion: '1.4.1' }])).toThrow(
'successful'
)
})
it('rejects incomplete, duplicate, mixed and failed evidence', () => {
const first = report(1, { a: 100 })
expect(() => importUnitTimingReports([first])).toThrow('complete')
@@ -186,38 +83,6 @@ function withReporterOutputs(run) {
}
describe('optional unit phase diagnostics', () => {
it('leaves the timing report identical and writes nothing extra when disabled', () => {
withReporterOutputs(({ timingPath, phasePath }) => {
const modules = [
phaseModule(
'src/example.test.ts',
phaseDiagnostic({ importDurations: { dependency: { selfTime: 100, totalTime: 200 } } })
)
]
const reporter = new UnitTimingReporter()
reporter.onInit(phaseContext({ workersSpawned: 3, startupTime: 500 }))
reporter.onTestRunEnd(modules, [], 'passed')
const timing = readFileSync(timingPath, 'utf8')
expect(existsSync(phasePath)).toBe(false)
vi.stubEnv('ORCA_UNIT_PHASE_REPORT', phasePath)
reporter.onTestRunEnd(modules, [], 'passed')
expect(readFileSync(timingPath, 'utf8')).toBe(timing)
expect(JSON.parse(timing).timings).toEqual({ 'src/example.test.ts': 44 })
expect(JSON.parse(readFileSync(phasePath, 'utf8'))).toMatchObject({
sourceSha: 'phase-source',
runId: 'phase-run',
runAttempt: '3',
metric: 'module-phase-diagnostics-v1',
vitestVersion: '5.0.3',
shard: { index: 1, count: 5 },
status: 'passed',
unhandledErrors: 0,
workerTotals: { scope: 'vitest-session', workersSpawned: 3, startupTimeMs: 500 }
})
})
})
it('records fractions and project totals without retaining sampled import records', () => {
const report = buildUnitPhaseReport(
phaseContext(),
@@ -271,73 +136,6 @@ describe('optional unit phase diagnostics', () => {
expect(JSON.stringify(report)).not.toContain('importDurations')
})
it('reports successful worker startup counters for the current run separately', () => {
withReporterOutputs(({ phasePath }) => {
vi.stubEnv('ORCA_UNIT_PHASE_REPORT', phasePath)
const state = { workersSpawned: 2, startupTime: 10 }
const reporter = new UnitTimingReporter()
reporter.onInit(phaseContext(state))
reporter.onTestRunStart()
state.workersSpawned = 5
state.startupTime = 60.25
reporter.onTestRunEnd([phaseModule('src/example.test.ts')], [], 'passed')
expect(JSON.parse(readFileSync(phasePath, 'utf8')).workerTotals).toEqual({
scope: 'test-run',
workersSpawned: 3,
startupTimeMs: 50.25
})
})
})
it('caps file detail while keeping aggregates from omitted files', () => {
const module = phaseModule('src/repeated.test.ts')
const modules = Array.from({ length: UNIT_PHASE_FILE_LIMIT }, () => module)
modules.push(
phaseModule(
'src/omitted.test.ts',
phaseDiagnostic({
collectDuration: 11,
importDurations: { dependency: { selfTime: 2, totalTime: 3 } }
})
)
)
const report = buildUnitPhaseReport(phaseContext(), modules, [], 'passed')
expect(report.files).toHaveLength(UNIT_PHASE_FILE_LIMIT)
expect(report).toMatchObject({
fileLimit: UNIT_PHASE_FILE_LIMIT,
filesSeen: UNIT_PHASE_FILE_LIMIT + 1,
filesOmitted: 1,
phases: { collectDuration: UNIT_PHASE_FILE_LIMIT * 30.25 + 11 },
projects: [
{
files: UNIT_PHASE_FILE_LIMIT + 1,
sampledImports: { entries: 1, selfTimeMs: 2, totalTimeMs: 3 }
}
]
})
})
it('marks unavailable counters, phases and worker IDs without inventing measurements', () => {
const report = buildUnitPhaseReport(
phaseContext({ workersSpawned: -1, startupTime: Number.NaN }),
[phaseModule('src/unavailable.test.ts', {})],
[],
'interrupted'
)
expect(report.workerTotals).toEqual({
scope: 'vitest-session',
workersSpawned: null,
startupTimeMs: null
})
expect(report.files[0]).toMatchObject({
workerId: null,
concurrencyId: null,
phases: { collectDuration: null }
})
expect(report.phaseSamples.collectDuration).toBe(0)
expect(report.status).toBe('interrupted')
})
it.each(['unwritable', 'same as timing'])(
'preserves timing evidence when the optional output is %s',
(target) => {
@@ -1,9 +1,7 @@
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it } from 'vitest'
import { runProcessSync } from '@orca/process-host'
import {
finishModuleCache,
moduleCacheIdentity,
@@ -35,42 +33,6 @@ function options() {
}
describe('persistent unit module cache boundary', () => {
it('separates hosts, runtimes, config, lockfiles, roots, shards and experiments', () => {
const original = options()
const identity = moduleCacheIdentity(original)
const anotherRoot = options().root
for (const update of [
{ root: anotherRoot },
{ policyHash: 'c'.repeat(64) },
{ installedLockHash: 'd'.repeat(64) },
{ platform: 'win32' },
{ arch: 'x64' },
{ nodeEnv: 'production' },
{ namespace: 'comparison' },
{ shard: { index: 2, count: 5 } },
{ shard: { index: 1, count: 10 } },
{ versions: { ...original.versions, node: '26.6.0' } },
{ versions: { ...original.versions, bun: '1.4.4' } },
{ versions: { ...original.versions, vitest: '5.0.4' } }
]) {
const next = moduleCacheIdentity({ ...original, ...update })
expect(next.key).not.toBe(identity.key)
expect(next.path).toBe(identity.path)
}
expect(moduleCacheIdentity(original)).toEqual(identity)
})
it.each([
{ cacheRoot: '' },
{ policyHash: '' },
{ installedLockHash: '' },
{ versions: { node: '24', bun: '1.4.3', vitest: '5.0.3' } },
{ shard: { index: 0, count: 5 } },
{ shard: { index: 6, count: 5 } }
])('refuses an incomplete identity %j', (update) => {
expect(() => moduleCacheIdentity({ ...options(), ...update })).toThrow('incomplete')
})
it.each([false, true])(
'starts cold and discards unusable restored bytes (hit %s)',
async (hit) => {
@@ -83,38 +45,6 @@ describe('persistent unit module cache boundary', () => {
expect(() => readFileSync(join(identity.path, 'untrusted'))).toThrow()
}
)
it.each(['warm', 'cold'])(
'does not write unused transforms on a consumer miss but retains producer writes (%s)',
(mode) => {
const identity = moduleCacheIdentity(options())
mkdirSync(join(identity.root, 'ci-shards'))
writeFileSync(
join(identity.root, 'ci-shards/unit-module-cache-identity.json'),
JSON.stringify(identity)
)
const envFile = join(identity.root, 'github-env')
writeFileSync(envFile, '')
const result = runProcessSync({
program: process.execPath,
args: [fileURLToPath(new URL('./ci-unit-module-cache.mjs', import.meta.url)), 'prepare'],
cwd: identity.root,
env: {
...process.env,
GITHUB_ENV: envFile,
ORCA_UNIT_CACHE_MODE: mode,
ORCA_UNIT_CACHE_RESTORE_HIT: 'false'
}
})
expect(result.code, result.stderr).toBe(0)
expect(readFileSync(envFile, 'utf8')).toBe(
mode === 'warm' ? 'ORCA_UNIT_MODULE_CACHE_PATH=\n' : ''
)
const report = JSON.parse(
readFileSync(join(identity.root, 'ci-shards/unit-module-cache.json'), 'utf8')
)
expect(report.available).toBe(false)
}
)
it('restores a matching cache produced from an earlier source', async () => {
const identity = moduleCacheIdentity(options())
@@ -12,16 +12,6 @@ const plan = {
candidateFiles: ['a']
}
it('does not present full fallback runs as selection-validation evidence', () => {
const records = [record(1, 'a', 'passed'), record(2, 'b', 'passed')].map((row) => ({
...row,
plan: { ...plan, selectionAvailable: false }
}))
expect(reviewUnitSelection(records)[0]).toMatchObject({
completeFullRun: true,
selectionEvaluated: false
})
})
const record = (index, file, state) => ({
plan,
timing: {
@@ -85,19 +75,3 @@ it('does not call incomplete, duplicate, interrupted or selected evidence a full
expect(reviewUnitSelection(rows).map((row) => row.completeFullRun)).toEqual([false])
}
})
it('requires all ten full assignments exactly once for complete evidence', () => {
const files = Array.from({ length: 10 }, (_, index) => `retained-${index}.test.ts`)
const tenPlan = { ...plan, files, candidateFiles: files }
const records = files.map((file, index) => {
const row = record(index + 1, file, 'passed')
return {
...row,
plan: tenPlan,
timing: { ...row.timing, shard: { index: index + 1, count: 10 } }
}
})
expect(reviewUnitSelection(records)[0].completeFullRun).toBe(true)
expect(reviewUnitSelection(records.slice(0, -1))[0].completeFullRun).toBe(false)
expect(reviewUnitSelection([...records.slice(0, -1), records[0]])[0].completeFullRun).toBe(false)
})
@@ -2,39 +2,9 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { runProcess } from '@orca/process-host'
import { runInNewContext } from 'node:vm'
import { expect, it } from 'vitest'
import { parse } from 'yaml'
const release = parse(readFileSync('.github/workflows/release-cut.yml', 'utf8'))
const audit = release.jobs['dependency-security']
const publish = release.jobs['publish-release']
function evaluate(expression, tag, result) {
const needs = Object.fromEntries(publish.needs.map((job) => [job, { result: 'success' }]))
needs.cut.outputs = { tag, should_release: 'true' }
needs['dependency-security'] = { result }
return runInNewContext(expression.replace(/needs\.([\w-]+)/g, 'needs["$1"]'), {
needs,
cancelled: () => false,
contains: (value, part) => value.includes(part)
})
}
it('audits stable releases without making publication wait for the scan', () => {
expect(publish.needs).not.toContain('dependency-security')
for (const tag of ['v1.5.0', 'v2.0.1']) {
expect(evaluate(audit.if, tag, 'success')).toBe(true)
for (const result of ['success', 'failure', 'cancelled', 'skipped', '', undefined]) {
expect(evaluate(publish.if, tag, result)).toBe(true)
}
}
for (const tag of ['v1.5.0-rc.1', 'v1.5.0-rc.1.perf']) {
expect(evaluate(audit.if, tag, 'skipped')).toBe(false)
expect(evaluate(publish.if, tag, 'skipped')).toBe(true)
}
})
it('extracts release data while excluding executable package and Cargo configuration', async () => {
const root = mkdtempSync(join(tmpdir(), 'release audit data '))
const source = join(root, 'source')
@@ -1,78 +0,0 @@
import { createRequire } from 'node:module'
import { setImmediate } from 'node:timers/promises'
import { expect, it } from 'vitest'
const builderRequire = createRequire(createRequire(import.meta.url).resolve('electron-builder'))
const require = createRequire(builderRequire.resolve('app-builder-lib'))
// Initialize the package root before submodules to preserve its CJS dependency order.
const { Platform } = require('app-builder-lib')
const { PlatformPackager } = require('app-builder-lib/out/platformPackager')
const { ArchiveTarget } = require('app-builder-lib/out/targets/ArchiveTarget')
const { DmgTarget } = require('dmg-builder/out/dmg')
const { computeArchToTargetNamesMap } = require('app-builder-lib/out/targets/targetFactory')
const { AsyncTaskManager } = require('builder-util')
const { CancellationToken } = require('builder-util-runtime')
it('the pinned builder reaches both signed slices before either real archive target passes its gate', async () => {
let release
const barrier = new Promise((resolve) => {
release = resolve
})
const events = []
const packager = {
platform: Platform.MAC,
config: {},
appInfo: { version: '1.0.0' },
platformSpecificBuildOptions: {},
info: {
cancellationToken: new CancellationToken(),
emitArtifactBuildStarted: async ({ arch }) => {
events.push(`wait:${arch}`)
await barrier
events.push(`pass:${arch}`)
throw new Error('STOP_BEFORE_ARTIFACT_IO')
}
},
expandArtifactNamePattern: (_options, extension, arch) => `fixture-${arch}.${extension}`
}
const archive = new ArchiveTarget('zip', '/unused', packager)
const targets = [archive, new DmgTarget(packager, '/unused')]
const manager = new AsyncTaskManager(packager.info.cancellationToken)
for (const arch of [1, 3]) {
events.push(`signed:${arch}`)
PlatformPackager.prototype.packageInDistributableFormat.call(
packager,
'/unused.app',
arch,
targets,
manager
)
await setImmediate()
}
expect(events.filter((event) => event.startsWith('signed:'))).toEqual(['signed:1', 'signed:3'])
expect(events.filter((event) => event.startsWith('wait:'))).toHaveLength(4)
expect(events.some((event) => event.startsWith('pass:'))).toBe(false)
release()
manager.addTask(archive.finishBuild())
await expect(manager.awaitTasks()).rejects.toThrow('STOP_BEFORE_ARTIFACT_IO')
expect(events.filter((event) => event.startsWith('pass:'))).toHaveLength(4)
})
it('explicit archive targets keep the configured dual-architecture defaults out of each matrix job', () => {
const packager = {
platformSpecificBuildOptions: {
target: [
{ target: 'dmg', arch: ['x64', 'arm64'] },
{ target: 'zip', arch: ['x64', 'arm64'] }
]
}
}
for (const arch of [1, 3]) {
const targets = computeArchToTargetNamesMap(
new Map([[arch, ['dmg', 'zip']]]),
packager,
Platform.MAC
)
expect([...targets]).toEqual([[arch, ['dmg', 'zip']]])
}
})
@@ -1,4 +1,4 @@
import { cp, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
import { cp, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -47,25 +47,4 @@ describe('verify packaged plugin resources', () => {
await rm(resourcesDir, { recursive: true, force: true })
}
})
it('rejects a CRLF checkout of the launch tree', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-packaged-plugins-'))
try {
const launchRoot = await copyIndexedLaunchTree(resourcesDir)
for (const entry of await readdir(launchRoot, { recursive: true })) {
const path = join(launchRoot, entry)
if (!(await stat(path)).isFile()) {
continue
}
await writeFile(path, (await readFile(path, 'utf8')).replace(/\r?\n/g, '\r\n'))
}
// Every plugin is rewritten; assert first sorted mismatch without pinning reorderable plugin name.
expect(() => verifyPackagedPluginResources(resourcesDir)).toThrow(
/packaged bytes do not match stablyai\./
)
} finally {
await rm(resourcesDir, { recursive: true, force: true })
}
})
})
@@ -48,20 +48,6 @@ describe('verify-localization-catalog', () => {
expect(readJson(path.join(localesDir, 'es.json'))).toEqual({})
})
it('bootstraps keys referenced only through translateSearchKeyword', async () => {
const { root, localesDir } = makeProject({
sourceText:
"import { translateSearchKeyword } from '@/components/settings/settings-search-keywords'\nexport const keywords = translateSearchKeyword('auto.components.settings.example.search.scroll', 'scroll')\n"
})
await expect(verifyLocalizationCatalog(root, { fix: false })).resolves.toBe(1)
await expect(verifyLocalizationCatalog(root, { fix: true })).resolves.toBe(0)
expect(readJson(path.join(localesDir, 'en.json'))).toEqual({
auto: { components: { settings: { example: { search: { scroll: 'scroll' } } } } }
})
})
it.each([
['en', false],
['en', true],
@@ -109,32 +95,6 @@ describe('verify-localization-catalog', () => {
})
})
it('accepts sparse target catalogs when existing placeholders match', async () => {
const { root } = makeProject({
sourceText:
"import { translate } from '@/i18n/i18n'\nexport const label = translate('auto.example.greeting', 'Hello {{name}}', { name: 'Orca' })\n",
enCatalog: {
auto: { example: { greeting: 'Hello {{name}}', untranslated: 'English only' } }
},
esCatalog: { auto: { example: { greeting: 'Hola {{name}}' } } }
})
await expect(verifyLocalizationCatalog(root, { fix: false })).resolves.toBe(0)
})
it('rejects one key reused for two different sentences', async () => {
const { root } = makeProject({
sourceText:
"import { translate } from '@/i18n/i18n'\nexport const left = translate('auto.example.move', 'Move {{value0}} left', { value0: 'A' })\nexport const right = translate('auto.example.move', 'Move {{value0}} right', { value0: 'A' })\n",
enCatalog: { auto: { example: { move: 'Move {{value0}} left' } } }
})
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
await expect(verifyLocalizationCatalog(root, { fix: false })).resolves.toBe(1)
expect(error.mock.calls.flat().join('\n')).toContain('auto.example.move')
error.mockRestore()
})
it('refuses to --fix a missing key reused for two different sentences', async () => {
const { root, localesDir } = makeProject({
sourceText:
@@ -160,118 +120,6 @@ describe('verify-localization-catalog', () => {
expect(readJson(path.join(localesDir, 'en.json'))).toEqual({})
})
it('accepts Russian few/many forms only for an existing plural family', async () => {
const { root, localesDir } = makeProject({
sourceText: 'export {}\n',
enCatalog: { images_one: '{{count}} image', images_other: '{{count}} images' }
})
const russianPath = path.join(localesDir, 'ru.json')
writeJson(russianPath, {
images_few: '{{count}} изображения',
images_many: '{{count}} изображений'
})
await expect(verifyLocalizationCatalog(root)).resolves.toBe(0)
writeJson(russianPath, { unknown_many: '{{count}} изображений' })
await expect(verifyLocalizationCatalog(root)).resolves.toBe(1)
writeJson(russianPath, { images_many: '{{wrongCount}} изображений' })
await expect(verifyLocalizationCatalog(root)).resolves.toBe(1)
writeJson(russianPath, { images_two: '{{count}} изображения' })
await expect(verifyLocalizationCatalog(root)).resolves.toBe(1)
})
it('requires both English forms of a native plural call', async () => {
const { root, localesDir } = makeProject({
sourceText:
"import { translate } from '@/i18n/i18n'\nexport const files = (count: number) => translate('auto.example.files', '{{count}} files', { count, defaultValue_one: 'One file' })\nexport const selected = (count: number) => translate('auto.example.selected', '{{count}} selected', { count })\n",
enCatalog: { auto: { example: { selected: '{{count}} selected' } } }
})
const report = vi.spyOn(console, 'error').mockImplementation(() => undefined)
try {
await expect(verifyLocalizationCatalog(root, { fix: false })).resolves.toBe(1)
} finally {
report.mockRestore()
}
await expect(verifyLocalizationCatalog(root, { fix: true })).resolves.toBe(0)
expect(readJson(path.join(localesDir, 'en.json'))).toEqual({
auto: {
example: {
selected: '{{count}} selected',
files_one: 'One file',
files_other: '{{count}} files'
}
}
})
})
it('commits CLDR plural forms a locale lacks beside its _other form', async () => {
const { root, localesDir } = makeProject({
sourceText: 'export {}\n',
enCatalog: {
files_one: 'One file',
files_other: '{{count}} files',
name: 'Name'
}
})
const frenchPath = path.join(localesDir, 'fr.json')
writeJson(frenchPath, { files_other: '{{count}} fichiers', name: 'Nom' })
const report = vi.spyOn(console, 'error').mockImplementation(() => undefined)
try {
await expect(verifyLocalizationCatalog(root, { fix: false })).resolves.toBe(1)
} finally {
report.mockRestore()
}
await expect(verifyLocalizationCatalog(root, { fix: true })).resolves.toBe(0)
expect(Object.entries(readJson(frenchPath))).toEqual([
['files_other', '{{count}} fichiers'],
['files_one', '{{count}} fichiers'],
['files_many', '{{count}} fichiers'],
['name', 'Nom']
])
await expect(verifyLocalizationCatalog(root, { fix: false })).resolves.toBe(0)
// Only an English form without {{count}} lets the locale add it; dropping it is still a mismatch.
writeJson(frenchPath, { files_other: 'fichiers', files_one: 'fichier', files_many: 'fichiers' })
const mismatch = vi.spyOn(console, 'error').mockImplementation(() => undefined)
try {
await expect(verifyLocalizationCatalog(root, { fix: false })).resolves.toBe(1)
} finally {
mismatch.mockRestore()
}
})
it('reports partial plugin catalog gaps but rejects malformed interpolation', async () => {
const { root } = makeProject({
sourceText: 'export {}\n',
enCatalog: {
auto: { first: 'First {{name}}', second: 'Second' }
},
esCatalog: {
auto: { first: 'Primero {{name}}', second: 'Segundo' }
}
})
const pluginCatalogPath = path.join(root, 'plugin-locale.json')
writeJson(pluginCatalogPath, {
auto: { first: 'Primeiro {{wrongName}}', pluginOnly: 'Plugin only' }
})
const report = vi.spyOn(console, 'log').mockImplementation(() => undefined)
try {
await expect(
verifyLocalizationCatalog(root, {
fix: false,
pluginCatalogs: [pluginCatalogPath]
})
).resolves.toBe(1)
expect(report).toHaveBeenCalledWith(expect.stringContaining('0/2 core keys'))
expect(report).toHaveBeenCalledWith(expect.stringContaining('interpolation mismatch'))
} finally {
report.mockRestore()
}
})
it('fails when a target catalog repeats a key', async () => {
const { root, localesDir } = makeProject({
sourceText:
@@ -11,34 +11,6 @@ function sourceEvidence(sourceText) {
}
describe('verify-localization-extraction', () => {
it('reports legacy drift without requiring a committed disposition database', () => {
const result = compareExtraction(
{ menu: { open: 'Open now {{name}}' } },
{ menu: { open: 'Open {{name}}', legacy: 'Legacy copy' } }
)
expect(result.orphans).toEqual(['menu.legacy'])
expect(result.fallbackDrift).toEqual(['menu.open'])
expect(result.placeholderMismatches).toEqual([])
})
it('reports dynamic defaults without treating empty extractor values as catalog copy', () => {
const result = compareExtraction(
{ menu: { dynamic: '' } },
{ menu: { dynamic: '{{count}} items' } }
)
expect(result.dynamicDefaults).toEqual(['menu.dynamic'])
expect(result.fallbackDrift).toEqual([])
expect(result.placeholderMismatches).toEqual([])
})
it('rejects undeclared keys even when their defaults are dynamic', () => {
const result = compareExtraction({ menu: { dynamic: '' } }, {})
expect(result.missingFromEnglish).toEqual(['menu.dynamic'])
})
it('rejects missing English declarations and incompatible placeholders', () => {
const result = compareExtraction(
{
@@ -54,27 +26,6 @@ describe('verify-localization-extraction', () => {
expect(result.placeholderMismatches).toEqual(['menu.open'])
})
it('tracks both plural defaults and keeps count-only keys singular', () => {
const result = compareExtraction(
{
files_one: '{{count}} file',
files_other: '{{count}} files',
selected_one: '{{count}} selected',
selected_other: '{{count}} selected'
},
{ files_one: 'One file', files_other: '{{count}} files', selected: '{{count}} selected' }
)
expect(result.missingFromEnglish).toEqual([])
expect(result.fallbackDrift).toEqual(['files_one'])
const dynamic = compareExtraction(
{ bg: { tasks_other: 'bg.tasks' } },
{ bg: { tasks_other: '{{count}} tasks' } }
)
expect(dynamic.dynamicDefaults).toEqual(['bg.tasks_other'])
})
it('keeps plural variants and data-structure keys that extraction cannot see', () => {
const evidence = sourceEvidence("const rows = [{ labelKey: 'rows.held' }]")
const extracted = new Map([['menu.count', '']])
@@ -1,5 +1,5 @@
import { build } from 'esbuild'
import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, expect, it } from 'vitest'
@@ -14,25 +14,15 @@ import { runProcessSync } from '@orca/process-host'
const directory = mkdtempSync(join(tmpdir(), 'orca-structured-provider-build-'))
const bundle = join(directory, 'orcad-server.js')
let serverMetafile
beforeAll(async () => {
serverMetafile = (await buildOrcadEntry(bundle)).metafile
await buildOrcadEntry(bundle)
}, 60_000)
afterAll(() => {
rmSync(directory, { recursive: true, force: true })
})
it('ships no runtime Electron imports in the actual server graph', () => {
const electronImporters = Object.entries(serverMetafile.inputs)
.filter(([, input]) =>
input.imports.some(({ path }) => path === 'electron' || path.startsWith('electron/'))
)
.map(([path]) => path)
expect(electronImporters).toEqual([])
})
it('loads the structured Claude SDK through the packaged server under plain Node', () => {
const loaded = runProcessSync({
program: process.execPath,
@@ -116,10 +106,6 @@ it.each(['import.meta', 'import.meta.dirname', 'import.meta.filename', 'import.m
}
)
it('keeps the server bundle ASCII, so V8 stores its source one byte per character', () => {
expect(findNonAsciiSource(readFileSync(bundle, 'utf8'))).toBeNull()
})
it('escapes only the trailing license comment, never code', () => {
const code = 'a=/[\u2726]/;'
const escaped = escapeLegalCommentTail(
@@ -130,22 +116,3 @@ it('escapes only the trailing license comment, never code', () => {
expect(findNonAsciiSource(escaped.slice(code.length))).toBeNull()
expect(escapeLegalCommentTail(code)).toBe(code)
})
it('keeps a build with every dark switch turned on ASCII', () => {
const darkBundle = join(directory, 'orcad-server-dark.js')
const built = runProcessSync({
program: process.execPath,
args: [
'--input-type=module',
'-e',
`const { buildOrcadEntry } = await import(${JSON.stringify(
new URL('./orcad-entry-build.mjs', import.meta.url).href
)}); await buildOrcadEntry(${JSON.stringify(darkBundle)})`
],
cwd: directory,
env: { ...process.env, ORCA_LAYOUT_OWNER: 'main', ORCA_SIDEBAR_INPUTS: 'main' },
timeoutMs: 120_000
})
expect(built.code, built.stderr.slice(-2_000)).toBe(0)
expect(findNonAsciiSource(readFileSync(darkBundle, 'utf8'))).toBeNull()
}, 150_000)
@@ -1,19 +0,0 @@
import { readFileSync } from 'node:fs'
import { expect, it } from 'vitest'
import { bundleDeclarativeFiles } from './build-plugin-declarative-runtime.mjs'
it('keeps the checked-in runtime, testing kit and test hooks in sync with their sources', async () => {
const bundles = await bundleDeclarativeFiles()
for (const { output, text } of bundles) {
expect({ output, fresh: readFileSync(output, 'utf8') === text }).toEqual({
output,
fresh: true
})
}
const runtime = bundles.find(({ output }) => output.endsWith('orca-runtime.mjs'))?.text ?? ''
// A bare import would fail in the guest: it has no module resolver beyond the import map.
expect(runtime).not.toMatch(/^\s*import\s/m)
// The kit must share the panel's runtime instance, never carry its own copy.
const testing = bundles.find(({ output }) => output.endsWith('orca-testing.mjs'))?.text ?? ''
expect(testing).toContain('"./orca-runtime.mjs"')
}, 60_000)
@@ -5,7 +5,6 @@ import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import {
isTagBuiltFromCurrentRef,
isReleaseCutDraft,
publishCompleteDraftReleases
} from './publish-complete-draft-releases.mjs'
import { getRequiredReleaseAssetNames } from './verify-release-required-assets.mjs'
@@ -47,53 +46,6 @@ function jsonResponse(body, init = {}) {
}
}
describe('isReleaseCutDraft', () => {
it('only accepts bot-authored desktop draft releases', () => {
expect(
isReleaseCutDraft({
draft: true,
tag_name: 'v1.4.2-rc.7',
author: { login: 'github-actions[bot]' }
})
).toBe(true)
expect(
isReleaseCutDraft({
draft: true,
tag_name: 'mobile-v0.0.7',
author: { login: 'github-actions[bot]' }
})
).toBe(false)
expect(
isReleaseCutDraft({
draft: true,
tag_name: 'v1.4.2',
author: { login: 'github-actions[bot]' }
})
).toBe(false)
expect(
isReleaseCutDraft({
draft: false,
tag_name: 'v1.4.2',
author: { login: 'github-actions[bot]' }
})
).toBe(false)
expect(
isReleaseCutDraft({
draft: false,
tag_name: 'v1.4.2-rc.7',
author: { login: 'github-actions[bot]' }
})
).toBe(false)
expect(
isReleaseCutDraft({
draft: true,
tag_name: 'v1.4.2-rc.7',
author: { login: 'release-maintainer' }
})
).toBe(false)
})
})
describe('isTagBuiltFromCurrentRef', () => {
it('accepts a tag whose release commit is built from the current ref', async () => {
await withGitRepo((repo) => {
@@ -106,17 +58,6 @@ describe('isTagBuiltFromCurrentRef', () => {
expect(isTagBuiltFromCurrentRef('v1.4.36-rc.6', { cwd: repo })).toBe(true)
})
})
it('rejects a stale tag when the current ref has moved on', async () => {
await withGitRepo((repo) => {
commit(repo, 'initial')
commit(repo, 'release: v1.4.36-rc.6')
git(repo, ['tag', 'v1.4.36-rc.6'])
commit(repo, 'fix: release packaging')
expect(isTagBuiltFromCurrentRef('v1.4.36-rc.6', { cwd: repo })).toBe(false)
})
})
})
describe('publishCompleteDraftReleases', () => {
@@ -3,11 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import {
highestRcForBase,
rcNumberFromReleaseSubject,
rcNumberFromTag
} from './release-rc-history.mjs'
import { highestRcForBase } from './release-rc-history.mjs'
function git(cwd, args) {
const result = runProcessSync({ program: 'git', args, cwd, timeoutMs: 10_000 })
@@ -39,29 +35,6 @@ function commit(cwd, message, { allowEmpty = true } = {}) {
}
describe('release RC history', () => {
it('parses only exact desktop RC tag suffixes', () => {
expect(rcNumberFromTag('1.4.36', 'v1.4.36-rc.7')).toBe(7)
expect(rcNumberFromTag('1.4.36', 'v1.4.36-rc.7-extra')).toBeNull()
expect(rcNumberFromTag('1.4.36', 'v1.4.35-rc.7')).toBeNull()
})
it('parses release commit subjects with optional slot markers', () => {
expect(rcNumberFromReleaseSubject('1.4.36', 'release: v1.4.36-rc.6')).toBe(6)
expect(
rcNumberFromReleaseSubject('1.4.36', 'release: v1.4.36-rc.6 [rc-slot:2026-05-30-03]')
).toBe(6)
expect(rcNumberFromReleaseSubject('1.4.36', 'release: v1.4.36-rc.6-extra')).toBeNull()
expect(rcNumberFromReleaseSubject('1.4.36', 'fix: v1.4.36-rc.6')).toBeNull()
})
it('counts a suffixed side-branch RC from its subject as well as its tag', () => {
expect(rcNumberFromTag('1.4.36', 'v1.4.36-rc.6.perf')).toBe(6)
expect(rcNumberFromReleaseSubject('1.4.36', 'release: v1.4.36-rc.6.perf')).toBe(6)
expect(
rcNumberFromReleaseSubject('1.4.36', 'release: v1.4.36-rc.6.perf [rc-slot:2026-05-30-03]')
).toBe(6)
})
it('keeps a suffixed RC counted once its tag is deleted', () => {
withGitRepo((repo) => {
commit(repo, 'initial')
@@ -1,136 +0,0 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it, vi } from 'vitest'
import { parse } from 'yaml'
const adhoc = parse(readFileSync('.github/workflows/adhoc-mac-build.yml', 'utf8'))
const publisher = parse(readFileSync('.github/workflows/dev-channel-win-publish.yml', 'utf8'))
const windows = parse(readFileSync('.github/workflows/dev-channel-win-build.yml', 'utf8'))
const finalSteps = adhoc.jobs['build-adhoc-mac'].steps
const publishSteps = publisher.jobs['publish-win'].steps
const macWait = publishSteps.find((step) => step.name === 'Wait for successful macOS publication')
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor
function execute(step, snapshots) {
let now = 0
let snapshot = 0
const calls = []
const github = {
rest: { actions: { listJobsForWorkflowRun: 'jobs', listWorkflowRunArtifacts: 'artifacts' } },
paginate: vi.fn(async (endpoint, input) => {
calls.push({ endpoint, input })
const current = snapshots[Math.min(snapshot, snapshots.length - 1)]
return current[endpoint] ?? []
})
}
const run = new AsyncFunction(
'github',
'context',
'process',
'Date',
'setTimeout',
step.with.script
)
return {
calls,
result: run(
github,
{ repo: { owner: 'owner', repo: 'repo' }, runId: 42 },
{ env: { ...step.env, MAC_JOB: 'build-adhoc-mac' } },
{ now: () => now },
(resolve) => {
now += 15_000
snapshot++
resolve()
}
)
}
}
const job = (name, conclusion) => ({
name,
status: conclusion ? 'completed' : 'in_progress',
conclusion
})
describe.each([['Windows', windows.jobs['build-win'].steps]])(
'%s release waits retain qualification and publication gates',
(_platform, buildSteps) => {
const templateWait = buildSteps.find(
(step) => step.name === 'Wait for the qualified orcad template'
)
it('allows desktop setup first, but waits for a qualified artifact from this run', async () => {
const { result, calls } = execute(templateWait, [
{ jobs: [job('orcad-template / cache', 'success')] },
{ jobs: [job('orcad-template / qualify / persistence (windows-11-arm)')] },
{ artifacts: [{ name: 'orcad-template', expired: true }] },
{ artifacts: [{ name: 'orcad-template', expired: false }] }
])
await result
expect(calls.filter((call) => call.endpoint === 'artifacts')).toHaveLength(4)
expect(calls.every((call) => call.input.run_id === 42)).toBe(true)
expect(buildSteps.indexOf(templateWait)).toBeGreaterThan(
buildSteps.findIndex((step) => step.name === 'Build app')
)
expect(buildSteps.indexOf(templateWait)).toBeLessThan(
buildSteps.findIndex((step) => step.name === 'Download the orcad deployment template')
)
})
it.each(['failure', 'cancelled', 'timed_out', 'action_required', 'startup_failure'])(
'refuses to package after template qualification ends with %s',
async (conclusion) => {
await expect(
execute(templateWait, [
{
jobs: [job('orcad-template / qualify / persistence (windows-11-arm)', conclusion)],
artifacts: [{ name: 'orcad-template', expired: false }]
}
]).result
).rejects.toThrow('Template qualification failed')
}
)
it('times out when no qualified artifact is produced', async () => {
await expect(execute(templateWait, [{}]).result).rejects.toThrow('Timed out')
})
}
)
it('keeps the release a draft until qualification and its cleanup finish', async () => {
const final = finalSteps.find(
(step) => step.name === 'Confirm final template qualification before publication'
)
const artifact = [{ name: 'orcad-template', expired: false }]
const { result, calls } = execute(final, [
{ artifacts: artifact, jobs: [job('orcad-template / qualify / desktop_template')] },
{ artifacts: artifact, jobs: [job('orcad-template / qualify / desktop_template', 'success')] }
])
await result
expect(calls.filter((call) => call.endpoint === 'artifacts')).toHaveLength(2)
expect(finalSteps.indexOf(final)).toBeLessThan(
finalSteps.findIndex((step) => step.id === 'publish_live')
)
})
it('prefetches Windows assets before waiting, then mints credentials after Mac succeeds', async () => {
const download = publishSteps.findIndex(
(step) => step.name === 'Download the staged Windows artifacts'
)
const wait = publishSteps.indexOf(macWait)
const token = publishSteps.findIndex((step) => step.name === 'Mint dev channel repo token')
expect(download).toBeLessThan(wait)
expect(wait).toBeLessThan(token)
await execute(macWait, [
{ jobs: [job('build-adhoc-mac')] },
{ jobs: [job('build-adhoc-mac', 'success')] }
]).result
})
it.each(['failure', 'cancelled', 'skipped', 'timed_out'])(
'refuses Windows publication when Mac ends with %s',
async (conclusion) => {
await expect(
execute(macWait, [{ jobs: [job('build-adhoc-mac', conclusion)] }]).result
).rejects.toThrow('macOS publication did not succeed')
}
)
@@ -1,307 +0,0 @@
import { execFileSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { parse } from 'yaml'
const RELEASE_WORKFLOW = '.github/workflows/release-cut.yml'
const EXPECTED_MATRIX = {
'.github/workflows/docs.yml#check': { contents: 'read' },
'.github/workflows/docs.yml#production': { contents: 'read' },
'.github/workflows/docs.yml#release_gate': { contents: 'read' },
'.github/workflows/e2e.yml#build': { contents: 'read' },
'.github/workflows/e2e.yml#changed-e2e': { contents: 'read' },
'.github/workflows/e2e.yml#e2e': { contents: 'read' },
'.github/workflows/e2e.yml#orcad-serve-mode-switch': { contents: 'read' },
'.github/workflows/e2e.yml#orcad-serve-mode-switch-windows': { contents: 'read' },
'.github/workflows/e2e.yml#orcad-ssh-docker': { contents: 'read' },
'.github/workflows/e2e.yml#ssh-browser-network-route': { contents: 'read' },
'.github/workflows/homebrew-bump.yml#bump-cask': { contents: 'read' },
'.github/workflows/release-mac-build.yml#build-mac': { actions: 'read', contents: 'write' },
'.github/workflows/release-mac-build.yml#qualification-template': {
actions: 'read',
contents: 'read'
},
...Object.fromEntries(
[
'changes',
'desktop_template',
'linux_glibc217_compat',
'linux_glibc_floor',
'linux_musl',
'mobile_web_bundle',
'persistence'
].map((job) => [
`.github/workflows/release-mac-build.yml#qualification-template -> .github/workflows/qualified-orcad-template.yml#qualify -> .github/workflows/node-server-tests.yml#${job}`,
job === 'desktop_template' ? { actions: 'read', contents: 'read' } : { contents: 'read' }
])
),
...Object.fromEntries(
[
'.github/workflows/release-mac-build.yml#qualification-template',
`${RELEASE_WORKFLOW}#orcad-template`
].flatMap((caller) =>
['cache', 'qualify', 'save'].map((job) => [
`${caller} -> .github/workflows/qualified-orcad-template.yml#${job}`,
job === 'qualify' ? { actions: 'read', contents: 'read' } : { contents: 'read' }
])
)
),
[`${RELEASE_WORKFLOW}#build`]: { actions: 'read', contents: 'write' },
[`${RELEASE_WORKFLOW}#build-mac`]: { actions: 'write', contents: 'read' },
[`${RELEASE_WORKFLOW}#verify-mac-build`]: { actions: 'read', contents: 'read' },
[`${RELEASE_WORKFLOW}#create-release`]: { contents: 'write' },
[`${RELEASE_WORKFLOW}#cut`]: { contents: 'write' },
[`${RELEASE_WORKFLOW}#dependency-security`]: { contents: 'read' },
[`${RELEASE_WORKFLOW}#dependency-security -> .github/workflows/dependency-security.yml#javascript`]:
{ contents: 'read' },
[`${RELEASE_WORKFLOW}#dependency-security -> .github/workflows/dependency-security.yml#rust`]: {
contents: 'read'
},
[`${RELEASE_WORKFLOW}#docs-production-dispatch`]: { actions: 'write' },
[`${RELEASE_WORKFLOW}#homebrew-bump`]: { contents: 'read' },
[`${RELEASE_WORKFLOW}#homebrew-bump -> .github/workflows/homebrew-bump.yml#bump-cask`]: {
contents: 'read'
},
[`${RELEASE_WORKFLOW}#homebrew-bump-published-rc-draft`]: { contents: 'read' },
[`${RELEASE_WORKFLOW}#homebrew-bump-published-rc-draft -> .github/workflows/homebrew-bump.yml#bump-cask`]:
{
contents: 'read'
},
[`${RELEASE_WORKFLOW}#orcad-template`]: { actions: 'read', contents: 'read' },
[`${RELEASE_WORKFLOW}#orcad-template -> .github/workflows/qualified-orcad-template.yml#qualify -> .github/workflows/node-server-tests.yml#changes`]:
{
contents: 'read'
},
[`${RELEASE_WORKFLOW}#orcad-template -> .github/workflows/qualified-orcad-template.yml#qualify -> .github/workflows/node-server-tests.yml#desktop_template`]:
{
actions: 'read',
contents: 'read'
},
[`${RELEASE_WORKFLOW}#orcad-template -> .github/workflows/qualified-orcad-template.yml#qualify -> .github/workflows/node-server-tests.yml#linux_glibc217_compat`]:
{
contents: 'read'
},
[`${RELEASE_WORKFLOW}#orcad-template -> .github/workflows/qualified-orcad-template.yml#qualify -> .github/workflows/node-server-tests.yml#linux_glibc_floor`]:
{
contents: 'read'
},
[`${RELEASE_WORKFLOW}#orcad-template -> .github/workflows/qualified-orcad-template.yml#qualify -> .github/workflows/node-server-tests.yml#linux_musl`]:
{
contents: 'read'
},
[`${RELEASE_WORKFLOW}#orcad-template -> .github/workflows/qualified-orcad-template.yml#qualify -> .github/workflows/node-server-tests.yml#mobile_web_bundle`]:
{
contents: 'read'
},
[`${RELEASE_WORKFLOW}#orcad-template -> .github/workflows/qualified-orcad-template.yml#qualify -> .github/workflows/node-server-tests.yml#persistence`]:
{
contents: 'read'
},
[`${RELEASE_WORKFLOW}#post-release-e2e`]: { actions: 'write' },
[`${RELEASE_WORKFLOW}#publish-release`]: { contents: 'write' },
[`${RELEASE_WORKFLOW}#release-javascript`]: { contents: 'read' },
[`${RELEASE_WORKFLOW}#release-javascript -> .github/workflows/release-javascript.yml#bundle`]: {
contents: 'read'
},
[`${RELEASE_WORKFLOW}#release-preflight`]: { contents: 'read' },
[`${RELEASE_WORKFLOW}#skill-sharing-linux-floor-release-gate`]: { contents: 'read' },
[`${RELEASE_WORKFLOW}#skill-sharing-release-gate`]: { contents: 'read' },
[`${RELEASE_WORKFLOW}#terminal-rendering-golden`]: { contents: 'read' },
[`${RELEASE_WORKFLOW}#terminal-rendering-release-evidence`]: { contents: 'read' }
}
const PUBLISH_TAG_JOBS = new Set(['build', 'create-release'])
const RELEASE_TAG_EXECUTION_JOBS = [
'build',
'create-release',
'skill-sharing-linux-floor-release-gate',
'skill-sharing-release-gate',
'terminal-rendering-golden',
'terminal-rendering-release-evidence'
]
const REUSABLE_CALL_JOBS = ['homebrew-bump', 'homebrew-bump-published-rc-draft']
function readWorkflow(relativePath) {
const ref = process.env.RELEASE_CUT_WORKFLOW_REF
const source = ref
? execFileSync('git', ['show', `${ref}:${relativePath}`], { encoding: 'utf8' })
: readFileSync(relativePath, 'utf8')
return parse(source)
}
function normalizePermissions(permissions) {
if (!permissions || typeof permissions !== 'object' || Array.isArray(permissions)) {
throw new Error(`Expected an explicit permission map, received ${String(permissions)}`)
}
return Object.fromEntries(
Object.entries(permissions).sort(([left], [right]) => left.localeCompare(right))
)
}
const permissionEscalations = []
function intersectPermissions(granted, requested, identity) {
const rank = { none: 0, read: 1, write: 2 }
const scopes = new Set([...Object.keys(granted), ...Object.keys(requested)])
return Object.fromEntries(
[...scopes]
.map((scope) => {
const grantedLevel = granted[scope] ?? 'none'
const requestedLevel = requested[scope] ?? 'none'
if (rank[requestedLevel] > rank[grantedLevel]) {
permissionEscalations.push({
identity,
scope,
granted: grantedLevel,
requested: requestedLevel
})
}
return [scope, rank[grantedLevel] < rank[requestedLevel] ? grantedLevel : requestedLevel]
})
.filter(([, level]) => level !== 'none')
.sort(([left], [right]) => left.localeCompare(right))
)
}
function resolveWorkflowMatrix(workflow, workflowPath, inheritedPermissions, prefix = '') {
const workflowPermissions = workflow.permissions
? normalizePermissions(workflow.permissions)
: inheritedPermissions
return Object.entries(workflow.jobs).reduce((matrix, [jobName, job]) => {
const requested = job.permissions ? normalizePermissions(job.permissions) : workflowPermissions
if (!requested) {
throw new Error(`${workflowPath}#${jobName} has no resolvable permissions`)
}
const identity = prefix
? `${prefix} -> ${workflowPath}#${jobName}`
: `${workflowPath}#${jobName}`
const effective = inheritedPermissions
? intersectPermissions(inheritedPermissions, requested, identity)
: requested
matrix[identity] = effective
if (job.uses?.startsWith('./.github/workflows/')) {
const calledPath = job.uses.slice(2)
Object.assign(
matrix,
resolveWorkflowMatrix(readWorkflow(calledPath), calledPath, effective, identity)
)
}
return matrix
}, {})
}
function applyFault(workflow) {
if (process.env.RELEASE_CUT_PERMISSION_FAULT !== 'inherit-write') {
return workflow
}
workflow.permissions = { contents: 'write' }
delete workflow.jobs.cut.permissions
return workflow
}
function checkoutRef(job) {
return job.steps?.find((step) => step.uses === 'actions/checkout@v6')?.with?.ref
}
function discoverDispatchedWorkflowPaths(workflow) {
const names = new Set()
for (const job of Object.values(workflow.jobs)) {
for (const step of job.steps ?? []) {
for (const [key, value] of Object.entries(step.env ?? {})) {
if (key.endsWith('_WORKFLOW') && typeof value === 'string' && /\.ya?ml$/.test(value)) {
names.add(value)
}
}
for (const match of step.run?.matchAll(/\bgh workflow run ([\w.-]+\.ya?ml)\b/g) ?? []) {
names.add(match[1])
}
}
}
return [...names].sort().map((name) => `.github/workflows/${name}`)
}
function discoverStandaloneReusablePaths(workflow) {
return [
...new Set(
Object.values(workflow.jobs)
.map((job) => job.uses)
.filter((uses) => uses?.startsWith('./.github/workflows/'))
.map((uses) => uses.slice(2))
.filter((path) => readWorkflow(path).on?.workflow_dispatch)
)
].sort()
}
function releaseTagExecutionJobs(workflow) {
return Object.entries(workflow.jobs).filter(([, job]) => {
const checkoutIndex = job.steps?.findIndex((step) => step.uses === 'actions/checkout@v6') ?? -1
return (
checkoutRef(job) === 'refs/tags/${{ needs.cut.outputs.tag }}' &&
job.steps.slice(checkoutIndex + 1).some((step) => step.run || step.uses?.startsWith('./'))
)
})
}
describe('release-cut token permissions', () => {
const workflow = applyFault(readWorkflow(RELEASE_WORKFLOW))
const reachedWorkflowPaths = [
...discoverDispatchedWorkflowPaths(workflow),
...discoverStandaloneReusablePaths(workflow)
]
const matrix = reachedWorkflowPaths.reduce(
(result, workflowPath) =>
Object.assign(result, resolveWorkflowMatrix(readWorkflow(workflowPath), workflowPath)),
resolveWorkflowMatrix(workflow, RELEASE_WORKFLOW)
)
it('keeps the complete effective job and reusable-workflow matrix least-privileged', () => {
expect(permissionEscalations).toEqual([])
expect(matrix).toEqual(EXPECTED_MATRIX)
})
it('runs release-tagged non-publishing code with read-only contents access', () => {
const tagJobs = releaseTagExecutionJobs(workflow)
expect(tagJobs.map(([jobName]) => jobName).sort()).toEqual(RELEASE_TAG_EXECUTION_JOBS)
for (const [jobName] of tagJobs) {
if (!PUBLISH_TAG_JOBS.has(jobName)) {
expect(matrix[`${RELEASE_WORKFLOW}#${jobName}`]).toEqual(
jobName === 'orcad-template'
? { actions: 'read', contents: 'read' }
: { contents: 'read' }
)
}
}
})
it('keeps fork, tag, and reusable-workflow boundaries explicit', () => {
expect(workflow.jobs.cut.if).toBe("github.repository == 'stablyai/orca'")
expect(checkoutRef(workflow.jobs.cut)).toBe(
"${{ github.event_name == 'schedule' && 'main' || inputs.ref }}"
)
for (const [jobName] of releaseTagExecutionJobs(workflow)) {
if (!PUBLISH_TAG_JOBS.has(jobName)) {
expect(workflow.jobs[jobName].needs).toBe('cut')
expect(workflow.jobs[jobName].if).toBe("needs.cut.outputs.should_release == 'true'")
}
}
for (const jobName of REUSABLE_CALL_JOBS) {
expect(workflow.jobs[jobName].uses).toBe('./.github/workflows/homebrew-bump.yml')
expect(matrix[`${RELEASE_WORKFLOW}#${jobName}`]).toEqual({ contents: 'read' })
}
const macWorkflow = readWorkflow('.github/workflows/release-mac-build.yml')
expect(macWorkflow.jobs['build-mac'].if).toBe(
"${{ !cancelled() && (!inputs.qualification_only || needs.qualification-template.result == 'success') && github.repository == 'stablyai/orca' }}"
)
expect(checkoutRef(macWorkflow.jobs['build-mac'])).toBe(
"${{ inputs.qualification_only && github.sha || format('refs/tags/{0}', inputs.tag) }}"
)
const e2eWorkflow = readWorkflow('.github/workflows/e2e.yml')
for (const jobName of Object.keys(e2eWorkflow.jobs)) {
expect(matrix[`.github/workflows/e2e.yml#${jobName}`]).toEqual({ contents: 'read' })
}
})
})
@@ -1,189 +0,0 @@
import { createHash } from 'node:crypto'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { spawnSync } = vi.hoisted(() => ({ spawnSync: vi.fn() }))
vi.mock('node:child_process', () => ({ spawnSync }))
let directory
let artifact
let originalArgv
let originalExitCode
const commands = () => spawnSync.mock.calls.map(([, args]) => args)
const signalRuns = () => commands().filter((args) => ['INT', 'TERM'].includes(args.at(-1)))
const succeeded = { status: 0, stdout: '', stderr: '' }
async function run(...options) {
process.argv = ['node', 'runner', '--appimage', artifact, ...options]
await import('./run-headless-serve-shutdown-docker.mjs')
}
beforeEach(() => {
vi.resetModules()
spawnSync.mockReset().mockReturnValue(succeeded)
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
directory = mkdtempSync(join(tmpdir(), 'orca-shutdown-matrix-'))
artifact = join(directory, 'original.AppImage')
writeFileSync(artifact, 'original package bytes')
originalArgv = process.argv
originalExitCode = process.exitCode
})
afterEach(() => {
process.argv = originalArgv
process.exitCode = originalExitCode
rmSync(directory, { recursive: true, force: true })
vi.restoreAllMocks()
})
describe('packaged shutdown matrix', () => {
it('shares extraction but isolates every entrypoint and signal', async () => {
await run('--all-entrypoints')
expect(commands().filter((args) => args[0] === 'build')).toHaveLength(1)
const startup = commands().filter((args) =>
args.includes('/usr/local/bin/run-appimage-desktop-startup-case')
)
const extraction = commands().filter((args) =>
args.some((arg) => arg.includes('120s /input/orca.AppImage --appimage-extract'))
)
expect(startup).toHaveLength(1)
expect(startup[0][startup[0].indexOf('--user') + 1]).toBe('0')
expect(startup[0][startup[0].indexOf('--cap-add') + 1]).toBe('SYS_ADMIN')
expect(extraction).toHaveLength(1)
expect(commands().indexOf(startup[0])).toBeLessThan(commands().indexOf(extraction[0]))
expect(signalRuns()).toHaveLength(6)
const names = new Set()
for (const [index, args] of signalRuns().entries()) {
const entrypoint = ['app', 'launcher', 'appimage'][Math.floor(index / 2)]
expect(args).toContain(`ORCA_TEST_ENTRYPOINT=${entrypoint}`)
expect(args).toContain(
`ORCA_SIGNAL_TARGET=${entrypoint === 'appimage' ? 'serving-electron' : 'app'}`
)
expect(args).toContain(
`ORCA_INT_DELIVERY=${entrypoint === 'appimage' ? 'pid' : 'foreground-process-group'}`
)
expect(args.at(-1)).toBe(index % 2 === 0 ? 'INT' : 'TERM')
expect(args).toContain(`${artifact}:/input/orca.AppImage:ro`)
expect(args.some((arg) => arg.endsWith(':/artifacts:ro'))).toBe(true)
expect(args).toContain('--rm')
names.add(args[args.indexOf('--name') + 1])
}
expect(names.size).toBe(6)
const evidence = console.log.mock.calls
.map(([line]) => line)
.filter((line) => line.startsWith('{'))
.map(JSON.parse)
expect(evidence).toHaveLength(3)
expect(
evidence.every(
(entry) =>
entry.sha256 === createHash('sha256').update('original package bytes').digest('hex')
)
).toBe(true)
expect(
commands()
.slice(-2)
.map((args) => args.slice(0, 2))
).toEqual([
['volume', 'rm'],
['image', 'rm']
])
})
it.each(['mount-denied', 'generic-exit', 'app-started', 'extract-assertion-failed'])(
'bounds desktop extraction fallback: %s',
async (scenario) => {
// Mount diagnostics captured in package job123685326492; Docker execution here is mocked.
const mountFailure = {
status: 127,
stdout: 'AppImage desktop launch mode: fuse\n',
stderr:
'FAIL: desktop launcher exited before the updater-setup-done marker (status=127)\n' +
'Cannot mount AppImage, please check your FUSE setup.\n' +
'/usr/bin/fusermount3: mount failed: Permission denied\n'
}
let attempts = 0
spawnSync.mockImplementation((_, args) => {
if (!args.includes('/usr/local/bin/run-appimage-desktop-startup-case')) {
return succeeded
}
attempts++
if (attempts > 1) {
return scenario === 'extract-assertion-failed'
? {
...succeeded,
status: 1,
stderr: 'FAIL: packaged PTY owning CLI command/profile mismatch'
}
: succeeded
}
if (scenario === 'generic-exit') {
return { ...mountFailure, stderr: 'Unexpected crash\n' }
}
if (scenario === 'app-started') {
return { ...mountFailure, stderr: `${mountFailure.stderr}[startup] app-ready t=10\n` }
}
return mountFailure
})
await (scenario === 'mount-denied'
? run('--all-entrypoints')
: expect(run('--all-entrypoints')).rejects.toThrow(
`failed with status ${scenario === 'extract-assertion-failed' ? 1 : 127}`
))
const startup = commands().filter((args) =>
args.includes('/usr/local/bin/run-appimage-desktop-startup-case')
)
const retries = scenario === 'mount-denied' || scenario === 'extract-assertion-failed'
expect(startup).toHaveLength(retries ? 2 : 1)
expect(startup[0]).not.toContain('ORCA_STARTUP_APPIMAGE_EXTRACT_AND_RUN=1')
if (retries) {
expect(startup[1]).toContain('ORCA_STARTUP_APPIMAGE_EXTRACT_AND_RUN=1')
expect(startup.every((args) => args.includes('--rm'))).toBe(true)
expect(startup.every((args) => args.includes(`${artifact}:/input/orca.AppImage:ro`))).toBe(
true
)
}
expect(signalRuns()).toHaveLength(scenario === 'mount-denied' ? 6 : 0)
expect(commands().at(-2).slice(0, 2)).toEqual(['volume', 'rm'])
}
)
it('attributes failures and still attempts later cases before cleanup', async () => {
spawnSync.mockImplementation((_, args) =>
args.at(-1) === 'INT' ? { ...succeeded, status: 7 } : succeeded
)
await expect(run('--all-entrypoints')).rejects.toThrow(
'app:INT:7, launcher:INT:7, appimage:INT:7'
)
expect(signalRuns()).toHaveLength(6)
expect(commands().at(-2).slice(0, 2)).toEqual(['volume', 'rm'])
})
it('cleans setup resources without running cases after failed extraction', async () => {
spawnSync.mockImplementation((_, args) =>
args.some((arg) => arg.includes('120s /input/orca.AppImage --appimage-extract'))
? { ...succeeded, status: 9 }
: succeeded
)
await expect(run('--all-entrypoints')).rejects.toThrow('docker run failed')
expect(signalRuns()).toHaveLength(0)
expect(
commands()
.slice(-2)
.map((args) => args.slice(0, 2))
).toEqual([
['volume', 'rm'],
['image', 'rm']
])
})
it('rejects ambiguous matrix overrides before invoking Docker', async () => {
await expect(run('--all-entrypoints', '--entrypoint', 'launcher')).rejects.toThrow(
'cannot be combined'
)
expect(spawnSync).not.toHaveBeenCalled()
})
})
@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest'
import { classifyPrJobs } from './pr-code-change-scope.mjs'
// Released-server launch contract must run when current desktop launch route or advertised client list changes.
describe('cross-version wire routing for the paired launch route', () => {
it.each([
'src/shared/structured-native-chat-launch-route.ts',
'src/renderer/src/lib/agent-session/launch/routing/agent-launch-routing.ts',
'src/renderer/src/runtime/paired-host-client-capabilities.ts',
'src/shared/electron-remote-runtime-client-capabilities.ts',
'src/shared/remote-runtime/remote-runtime-client-capabilities.ts'
])('runs the cross-version suites when %s changes', (file) => {
expect(classifyPrJobs([file])).toMatchObject({ should_run: true, 'cross-version-wire': true })
})
it('leaves them off for the route input builder, which no cross-version suite executes', () => {
expect(
classifyPrJobs([
'src/renderer/src/lib/agent-session/launch/routing/agent-launch-route-input.ts'
])
).toMatchObject({
should_run: true,
'cross-version-wire': false
})
})
})
@@ -1,36 +0,0 @@
import { describe, expect, it } from 'vitest'
import { classifyPrJobs } from './pr-code-change-scope.mjs'
// Route code the suite executes; dispatcher registration alone is not coverage (#24901 missed send-path changes).
describe('cross-version wire routing for the send path', () => {
it.each([
'src/shared/agent-session/failures/agent-session-wire-refusals.ts',
'src/shared/agent-session/lifecycle/structured-agent-session-mutation.ts',
'src/shared/agent-session/requests/structured-agent-session-send-mutation.ts',
'src/main/runtime/rpc/core.ts',
'src/main/runtime/rpc/errors.ts',
'src/main/runtime/rpc/orchestration-contract-fence.ts',
'src/main/runtime/rpc/orchestration-session-caller.ts',
'src/main/runtime/rpc/orchestration-legacy-compatibility.ts',
'src/main/runtime/rpc/orchestration-mutation-executor.ts',
'src/shared/orchestration-rpc-contract.ts',
'src/main/runtime/orchestration/db/schema/migrate.ts',
'src/main/runtime/rpc/ws-transport.ts',
'src/shared/web-origin-security.ts'
])('runs the cross-version suites when %s changes', (file) => {
expect(classifyPrJobs([file])).toMatchObject({ should_run: true, 'cross-version-wire': true })
})
it.each([
'src/shared/agent-session/requests/structured-agent-session-send-evidence.ts',
'src/shared/agent-session/view/structured-agent-session-composer.ts',
'src/shared/agent-session/structured-agent-session-reducer.ts',
'src/main/runtime/orchestration/turn-delivery/send-agent-turn.ts',
'src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts',
'src/main/runtime/rpc/orchestration-legacy-mail.ts',
'src/main/runtime/rpc/methods/orchestration/orchestration.ts',
'src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts'
])('leaves them off for %s, which no cross-version suite executes', (file) => {
expect(classifyPrJobs([file])).toMatchObject({ should_run: true, 'cross-version-wire': false })
})
})
@@ -1,45 +0,0 @@
import { describe, expect, it } from 'vitest'
import { classifyPrJobs } from './pr-code-change-scope.mjs'
describe('per-job path classification', () => {
it('keeps the client-only unit suite out of real Codex binary checks', () => {
const unit = 'src/main/codex/app-server/codex-app-server-client.test.ts'
const expected = {
should_run: true,
static_analysis: true,
typecheck: true,
git_compatibility: false,
codex_index_heal_contract: false,
xterm_patch_sync: false,
shell_contracts: false,
test: true,
orcad_browser: false,
mobile_web_app: false,
'cross-version-wire': false,
managed_hook_node18: false,
package: false,
package_windows: false
}
expect(classifyPrJobs([unit])).toMatchObject(expected)
expect(
classifyPrJobs([
unit,
'config/scripts/desktop-distribution/runtime-verification/process-host-build-dist.test.mjs',
'src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts',
'src/shared/worktree/id.test.ts'
])
).toMatchObject(expected)
for (const file of [
'src/main/codex/app-server/codex-app-server-client.ts',
'src/main/codex/app-server/codex-app-server-client-other.test.ts',
'src/main/codex/app-server/codex-app-server-client.test-fixture.ts',
'src/main/codex/history/index/codex-index-heal-binary-contract.test.ts',
'src/main/pty/shell-startup/codex-no-daemon-binary-contract.test.ts',
'src/main/codex/hooks/definitions/codex-hook-file-entry-binary-contract.test.ts',
'src/main/agent-launch/trust/agent-trust-presets.test.ts',
'.github/workflows/pr.yml'
]) {
expect(classifyPrJobs([unit, file]).codex_index_heal_contract, file).toBe(true)
}
})
})
@@ -1,225 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
hasNativeImeSourceChange,
PR_E2E_SOURCE_ROUTES,
selectPrE2eSpecs
} from './pr-e2e-source-routing.mjs'
/** The route that sends a change to the two-Electron restart-survival spec. */
const restartSurvivalRoute = PR_E2E_SOURCE_ROUTES.find(
(route) => route.id === 'client-hosted-browser.restart-survival'
)
describe('restart-survival E2E routing', () => {
// Keep restart-survival routing narrow to avoid two-Electron cost on every source change.
it.each([
'src/main/git/git-status.ts',
'src/renderer/src/components/tab-bar/BrowserTab.tsx',
'src/main/terminal/pty-manager.ts',
// The status/types entries name whole files, not a suffix any longer name may end with.
'src/shared/computer-use-runtime-types.ts',
'src/main/runtime/browser/browser-commands.test.ts',
'src/main/runtime/browser/browser-commands.test-fixture.ts',
'src/main/runtime/browser/browser-commands.fixture.ts',
'src/main/runtime/browser/browser-commands-extra.ts',
'src/main/runtime/browser/commands/browser-navigation.ts'
])('does not route %s', (path) => {
expect(restartSurvivalRoute.matches(path)).toBe(false)
})
})
describe('paired HTML preview E2E routing', () => {
const spec = 'tests/e2e/paired-remote-html-preview-local-render.spec.ts'
it.each([
'src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.tsx',
'src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx',
'src/main/browser/document-preview/doc-preview-protocol.ts',
'src/main/ipc/doc-preview-grant-ipc.ts',
'src/preload/doc-preview-link-interception.ts',
'src/shared/doc-preview-scheme.ts',
'tests/e2e/helpers/paired-html-preview-inventory.ts'
])('routes %s', (path) => {
expect(selectPrE2eSpecs([path])).toContain(spec)
})
it.each([
'src/main/ipc/doc-preview-grant-ipc.test.ts',
'src/renderer/src/components/browser-pane/BrowserPane.tsx'
])('does not route %s', (path) => {
expect(selectPrE2eSpecs([path])).not.toContain(spec)
})
})
describe('preview address-bar convergence E2E routing', () => {
const spec = 'tests/e2e/paired-preview-address-bar-convergence.spec.ts'
it.each([
'src/renderer/src/components/browser-pane/workspace-doc/doc-preview-address-edit.tsx',
'src/renderer/src/components/browser-pane/assemble-chrome/browser-address-bar-suggestions.ts',
'src/renderer/src/lib/workspace-doc-address-input.ts',
'src/renderer/src/store/slices/browser/pages/browser-page-conversion-actions.ts'
])('routes %s', (path) => {
expect(selectPrE2eSpecs([path])).toContain(spec)
})
it.each([
'src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts',
'src/renderer/src/components/browser-pane/assemble-chrome/BrowserAddressBar.tsx'
])('does not route %s', (path) => {
expect(selectPrE2eSpecs([path])).not.toContain(spec)
})
})
describe('PR E2E gate contract', () => {
it('routes only core xterm patches to both IME lanes across version updates', () => {
for (const file of [
'config/patches/@xterm__xterm@6.1.0-beta.336.patch',
'config/patches/xterm-src/@xterm__xterm@6.1.0-beta.336.src.patch',
'config/patches/@xterm__xterm@7.0.0.patch',
'config/patches/xterm-src/@xterm__xterm@7.0.0.src.patch'
]) {
const specs = selectPrE2eSpecs([file])
expect(hasNativeImeSourceChange([file]), file).toBe(true)
expect(specs, file).toContain('tests/e2e/terminal-ime-exact-byte.spec.ts')
expect(specs, file).toContain('tests/e2e/terminal-ibus-hangul-native.spec.ts')
}
for (const file of [
'config/patches/i18next-cli@1.74.2.patch',
'config/patches/node-pty@1.1.0.patch',
'config/patches/monaco-editor@0.55.1.patch',
'config/patches/@xterm__addon-webgl@0.20.0-beta.329.patch',
'config/patches/xterm-src/@xterm__addon-search@0.17.0-beta.330.src.patch',
'config/patches/xterm-upstream.json',
'config/patches/@xterm__xterm@7.0.0.patch.bak'
]) {
expect(hasNativeImeSourceChange([file]), file).toBe(false)
expect(selectPrE2eSpecs([file]), file).toEqual([])
}
const corePatch = 'config/patches/@xterm__xterm@6.1.0-beta.336.patch'
const mixedChanges = ['config/patches/i18next-cli@1.74.2.patch', corePatch]
expect(hasNativeImeSourceChange(mixedChanges)).toBe(true)
expect(selectPrE2eSpecs(mixedChanges)).toEqual(selectPrE2eSpecs([corePatch]))
})
})
describe('GitHub Projects E2E routing', () => {
it.each([
'src/renderer/src/components/github-project/columns.ts',
'src/renderer/src/store/github/projects/project-field-mutations.ts',
'src/main/github/project-view/project-field-mutations.ts',
'src/main/ipc/source-control/github-project-view-handlers.ts'
])('routes %s to the board spec', (file) => {
expect(selectPrE2eSpecs([file])).toContain('tests/e2e/github-project-board.spec.ts')
})
it('skips the board spec for unit tests and unrelated GitHub stores', () => {
for (const file of [
'src/renderer/src/store/github/projects/project-field-mutations.test.ts',
'src/renderer/src/store/github/cache/cache-model.ts'
]) {
expect(selectPrE2eSpecs([file]), file).not.toContain('tests/e2e/github-project-board.spec.ts')
}
})
})
describe('Terminal pane geometry E2E routing', () => {
const specs = [
'tests/e2e/issue-12656-terminal-link-tooltip.spec.ts',
'tests/e2e/terminal-pane-padding-edges.spec.ts'
]
it.each([
'src/renderer/src/assets/terminal.css',
'src/renderer/src/lib/pane-manager/pane-divider.ts',
'src/renderer/src/lib/pane-manager/pane-dom-creation.ts',
'src/renderer/src/lib/pane-manager/terminal-linkifier-hover-reset-on-mouseleave.ts'
])('routes %s to the pane geometry specs', (file) => {
expect(selectPrE2eSpecs([file])).toEqual(expect.arrayContaining(specs))
})
it('skips the pane geometry specs for their unit tests', () => {
const selected = selectPrE2eSpecs(['src/renderer/src/lib/pane-manager/pane-divider.test.ts'])
expect(selected).not.toContain(specs[0])
})
})
describe('Daemon mock modified-only source routing', () => {
const helper = 'src/main/daemon/providers/lifecycle/testing/daemon-init-dependency-mocks.ts'
const verified = { allowDaemonInitTestSupport: true }
it('omits the real D7 route only for the proven unit-support scope', () => {
expect(selectPrE2eSpecs([helper])).toContain('tests/e2e/orcad-serve-mode-switch.spec.ts')
expect(selectPrE2eSpecs([helper], undefined, verified)).toEqual([])
const companion =
'config/scripts/desktop-distribution/runtime-verification/process-host-build-dist.test.mjs'
expect(selectPrE2eSpecs([helper, companion], undefined, verified)).toEqual(
selectPrE2eSpecs([companion])
)
})
it.each([
{ files: [] },
{ files: [helper, 'src/main/daemon/daemon-init.ts'] },
{ files: [helper, 'package.json'] },
{ files: [helper, 'src/main/daemon/unknown-support.ts'] },
{ files: [helper, helper] }
])('retains existing routes for an uncertain or mixed vector $files', ({ files }) => {
expect(selectPrE2eSpecs(files, undefined, verified)).toEqual(selectPrE2eSpecs(files))
})
})
describe('runtime host status E2E routing', () => {
const spec = 'tests/e2e/runtime-host-status-recovery.spec.ts'
it.each([
'src/shared/remote-runtime/host-store/runtime-environment-pairing-replace-guards.ts',
'src/main/ipc/runtime-environments/runtime-environment-status-probe.ts',
'src/renderer/src/store/slices/runtime-status-refresh.ts'
])('routes %s', (path) => {
expect(selectPrE2eSpecs([path])).toContain(spec)
})
it('does not route unit tests of those sources', () => {
expect(
selectPrE2eSpecs(['src/renderer/src/store/slices/runtime-status-refresh.test.ts'])
).not.toContain(spec)
})
})
describe('startup exec readiness E2E routing', () => {
const spec = 'tests/e2e/paired-startup-exec-readiness.spec.ts'
it.each([
'src/main/daemon/sessions/session-shell-ready-barrier.ts',
'src/main/daemon/shell-readiness/post-ready-flush-gate.ts',
'src/main/pty/shell-startup/shell-templates.ts',
'tests/e2e/helpers/startup-exec-readiness-oracle.ts'
])('routes %s', (path) => {
expect(selectPrE2eSpecs([path])).toContain(spec)
})
it('does not route unit tests of those sources', () => {
expect(
selectPrE2eSpecs(['src/main/daemon/shell-readiness/testing/shell-ready.test.ts'])
).not.toContain(spec)
})
})
describe('agent descendant kill E2E routing', () => {
const spec = 'tests/e2e/agent-descendant-process-kill.spec.ts'
it.each([
'src/main/pty/process-retirement/pty-descendant-termination.ts',
'src/main/daemon/sessions/terminal-descendant-shutdown.ts',
'src/main/claude/agent-view/agent-view-service.ts'
])('routes %s', (file) => {
expect(selectPrE2eSpecs([file])).toContain(spec)
})
it('skips unit tests', () => {
expect(
selectPrE2eSpecs(['src/main/pty/process-retirement/pty-descendant-termination.test.ts'])
).not.toContain(spec)
})
})
describe('agent permission settings E2E routing', () => {
const spec = 'tests/e2e/agent-auto-permissions.spec.ts'
it.each([
'src/renderer/src/components/agent/launch-settings/AgentPermissionChoiceControls.tsx',
'src/renderer/src/components/settings/agents/permissions/AgentPermissionModeMenu.tsx',
'src/shared/agent-launch/permissions/tui-agent-permission-choice.ts'
])('routes %s', (file) => {
expect(selectPrE2eSpecs([file])).toContain(spec)
})
it('skips unit tests', () => {
expect(
selectPrE2eSpecs(['src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts'])
).not.toContain(spec)
})
})
@@ -1,6 +1,4 @@
import { beforeAll, describe, expect, it } from 'vitest'
import { classifyPrJobs } from './pr-code-change-scope.mjs'
import { selectPrE2eSpecs } from './pr-e2e-source-routing.mjs'
import {
buildUnitDependencyGraph,
collectUnitDependencyGraph,
@@ -46,59 +44,6 @@ function productConsumers(file, graph, unitFiles) {
)
}
describe('unit support routing', () => {
it.each(unitHarnesses)(
'keeps unit checks and lint while excluding packaging for %s',
(unitHarness) => {
const result = classifyPrJobs([unitHarness])
expect(result.should_run).toBe(true)
expect(result.static_analysis).toBe(true)
expect(result.typecheck).toBe(true)
expect(result.test).toBe(true)
expect(result.package).toBe(false)
expect(result.package_windows).toBe(false)
}
)
it.each(unitHarnesses)(
'retains packaging for unknown helpers and mixed product changes with %s',
(unitHarness) => {
for (const file of [
unitHarness.replace(/\.(tsx?)$/, '-next.$1'),
'src/renderer/src/runtime/web-session-tabs-sync-next-test-harness.ts',
'src/renderer/src/runtime/web-session-tabs-sync/snapshot-api.ts',
'src/renderer/src/components/native-chat/NativeChatStructuredSession.next-test-harness.tsx',
'src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx',
'src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts',
'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts'
]) {
const result = classifyPrJobs([unitHarness, file])
expect(result.should_run, file).toBe(true)
expect(result.test, file).toBe(true)
expect(result.package, file).toBe(
file !== 'src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts'
)
expect(result.package_windows, file).toBe(true)
}
}
)
it.each(unitHarnesses)('does not select product E2E for %s', (unitHarness) => {
expect(selectPrE2eSpecs([unitHarness])).toEqual([])
})
it('retains E2E selection for unknown helpers, product changes and selected specs', () => {
const spec = 'tests/e2e/paired-client-hosted-browser-restart-survival.spec.ts'
for (const file of [
'src/renderer/src/runtime/web-session-tabs-sync-next-test-harness.ts',
'src/renderer/src/runtime/web-session-tabs-sync/snapshot-api.ts',
spec
]) {
expect(selectPrE2eSpecs([harness, file]), file).toContain(spec)
}
})
})
describe('unit support import ownership', () => {
let graph
let unitFiles
@@ -1,39 +0,0 @@
import { describe, expect, it } from 'vitest'
import { hasWslSourceChange, selectPrE2eSpecs } from './pr-e2e-source-routing.mjs'
describe('real WSL terminal lane', () => {
it.each([
'config/scripts/runtime-verification/participation/verify-wsl-e2e-participation.mjs',
'config/scripts/runtime-verification/participation/verify-playwright-participation.mjs',
'src/main/wsl/discovery/wsl-availability.ts',
'src/main/wsl/execution/wsl-runner.ts',
'src/main/pty/shell-startup/wsl-orca-env.ts',
'src/shared/wsl-login-shell-command.ts',
'src/shared/shell/launch/shell-argument-quoting.ts',
'src/shared/windows-terminal-shell.ts',
'tests/e2e/helpers/wsl-golden-stub-agent.ts',
'tests/e2e/golden-tab-bar-agent-launch.spec.ts',
'tests/e2e/terminal-windows-shell-paste-ownership.spec.ts',
'tests/e2e/terminal-inline-images-windows.spec.ts',
'tests/e2e/wsl-bridge-no-background-boot.spec.ts',
'config/scripts/runtime-verification/participation/verify-wsl-no-background-boot-participation.mjs',
'.github/actions/setup-wsl-test-runtime/setup.ps1',
'.github/workflows/windows-wsl-e2e.yml'
])('routes %s to both WSL sentinels', (path) => {
expect(hasWslSourceChange([path])).toBe(true)
expect(selectPrE2eSpecs([path])).toEqual(
expect.arrayContaining([
'tests/e2e/golden-tab-bar-agent-launch.spec.ts',
'tests/e2e/terminal-windows-shell-paste-ownership.spec.ts'
])
)
})
it.each([
'docs/reference/wsl-command-execution.md',
'src/main/wsl-availability.test.ts',
'src/main/ssh/connection.ts'
])('excludes unrelated or unit-only change %s', (path) => {
expect(hasWslSourceChange([path])).toBe(false)
})
})
@@ -26,7 +26,7 @@ const LEAKED_NATIVE_GLOBALS = [
]
const toPosix = (filePath) => filePath.replaceAll('\\', '/')
// The two test bodies are the roots of the node test config, so no second list names them.
// The test bodies are the roots of the node test config, so no second list names them.
export function readNodeTestRoots(root = repoRoot) {
const config = JSON.parse(fs.readFileSync(path.join(root, NODE_TEST_PROJECT), 'utf8'))
return config.files.filter((file) => /\.test\.tsx?$/.test(file)).sort()
@@ -42,7 +42,7 @@ export function parseCompilerPass(output, code) {
return { ok: code === 0 && diagnostics.length === 0, code, diagnostics, files }
}
// Membership is the proof: both bodies, nothing else repository-owned that is not a declaration,
// Membership is the proof: all test bodies, nothing else repository-owned that is not a declaration,
// and no RN/Expo global file. Returns the problems; an empty list is a clean program.
export function checkNodeTestProgram(files, { realRoot, expected }) {
const prefix = `${toPosix(realRoot).replace(/\/$/, '')}/`
@@ -15,10 +15,6 @@ const ERROR_LINE = /^(\S.*?)\(\d+,\d+\): error TS\d+:/
// Tests outside the RN program. Checked transfers are the roots of tsconfig.test.node.json and must pass
// that strict program; the rest are legacy runtime-only allowances whose bodies nothing typechecks.
export const TESTS_OUTSIDE_PROGRAM = new Map([
[
'src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts',
'Checked transfer: strict Node program over emitted phone/host declarations (tsconfig.test.node.json)'
],
[
'src/components/WorktreeAgentList.runtime-lineage.test.tsx',
'Legacy runtime-only: the test body is not typechecked anywhere; it imports the desktop SQLite assignment projection, which does not check against RN libs, and its implementation sources keep their normal checks'
@@ -1,6 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import type { RpcClient } from '../transport/rpc-client'
import { FLOATING_WORKSPACE_WORKTREE_ID } from './floating-workspace'
import { WORKSPACE_ON_OTHER_RUNTIME } from '../../../src/shared/protocol-version'
import {
loadMobileAgentLaunchContext,
@@ -25,30 +24,6 @@ function createClient(
}
describe('mobile new-tab agent loading', () => {
it('detects agents for a folder workspace on its owning host without resolving a repo', async () => {
const client = createClient(async (method, params) => {
if (method === 'settings.get') {
return { ok: true, result: { settings: {} } }
}
if (method === 'preflight.detectAgents') {
expect(params).toEqual({ worktreeId: 'folder:fw-1' })
return { ok: true, result: ['claude'] }
}
throw new Error(`unexpected request: ${method}`)
})
await expect(
loadOptions({
client,
worktreeId: 'folder:fw-1',
hostRefusesOtherRuntime: true
})
).resolves.toEqual([{ agent: 'claude', label: 'Claude' }])
expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([
'preflight.detectAgents',
'settings.get'
])
})
function folderClient(args: {
connectionId?: string | null
groupConnectionId?: string
@@ -127,48 +102,6 @@ describe('mobile new-tab agent loading', () => {
})
}
it.each([
['local', {}, 'preflight.detectAgents'],
[
'explicit local pin overrides group SSH and runtime candidates',
{
executionHostId: 'local',
groupConnectionId: 'group-ssh',
repos: [{ path: '/project/repo', projectGroupId: 'pg-1', executionHostId: 'runtime:other' }]
},
'preflight.detectAgents'
],
['group SSH', { groupConnectionId: 'group-ssh' }, 'preflight.detectRemoteAgents'],
[
'workspace connection overrides group runtime',
{ connectionId: 'own-ssh', groupExecutionHostId: 'runtime:other' },
'preflight.detectRemoteAgents'
],
[
'workspace SSH override',
{ connectionId: 'own-ssh', groupConnectionId: 'group-ssh' },
'preflight.detectRemoteAgents'
],
[
'explicit host pin',
{ executionHostId: 'ssh:pinned', groupConnectionId: 'group-ssh' },
'preflight.detectRemoteAgents'
],
[
'inferred repo SSH',
{
repos: [{ path: '/project/repo', projectGroupId: 'pg-1', executionHostId: 'ssh:repo-ssh' }]
},
'preflight.detectRemoteAgents'
]
])('resolves an older host folder catalog: %s', async (_label, args, method) => {
const client = folderClient(args)
await expect(loadOptions({ client, worktreeId: 'folder:fw-1' })).resolves.toEqual([
{ agent: 'claude', label: 'Claude' }
])
expect(client.sendRequest.mock.calls.at(-1)?.[0]).toBe(method)
})
it.each([
['missing', { missing: true }],
['duplicate identity', { duplicate: true }],
@@ -228,23 +161,6 @@ describe('mobile new-tab agent loading', () => {
)
})
it.each(['folderWorkspace.list', 'projectGroup.list', 'repo.list'])(
'never probes after an incompatible legacy %s reply',
async (failedMethod) => {
const base = folderClient({})
const client = createClient(async (method, params) => {
if (method === failedMethod) {
return { ok: true, result: null }
}
return base.sendRequest(method, params)
})
await expect(loadOptions({ client, worktreeId: 'folder:fw-1' })).rejects.toThrow()
expect(
client.sendRequest.mock.calls.some(([method]) => method.startsWith('preflight.'))
).toBe(false)
}
)
it.each([false, true])(
'preserves transport failure without a wrong-host retry (modern=%s)',
async (modern) => {
@@ -270,117 +186,6 @@ describe('mobile new-tab agent loading', () => {
}
)
it('keeps a modern unserved SSH refusal without retrying on the paired host', async () => {
const client = createClient(async (method) =>
method === 'settings.get'
? { ok: true, result: { settings: {} } }
: { ok: false, error: { code: 'runtime_error', message: 'SSH host not served' } }
)
await expect(
loadOptions({
client,
worktreeId: 'folder:fw-1',
hostRefusesOtherRuntime: true
})
).rejects.toThrow('SSH host not served')
expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([
'preflight.detectAgents',
'settings.get'
])
})
it('preserves a modern host folder ownership refusal', async () => {
await expect(
loadOptions({
client: folderClient({ refused: true }),
worktreeId: 'folder:fw-1',
hostRefusesOtherRuntime: true
})
).rejects.toBeInstanceOf(MobileWorkspaceOnOtherRuntimeError)
})
it('detects agents locally for the floating workspace without listing repos', async () => {
const client = createClient(async (method) => {
if (method === 'settings.get') {
return {
ok: true,
result: { settings: { defaultTuiAgent: 'codex', disabledTuiAgents: [] } }
}
}
if (method === 'preflight.detectAgents') {
return { ok: true, result: ['claude', 'codex'] }
}
throw new Error(`unexpected request: ${method}`)
})
await expect(
loadOptions({
client,
worktreeId: FLOATING_WORKSPACE_WORKTREE_ID
})
).resolves.toEqual([
{ agent: 'codex', label: 'Codex' },
{ agent: 'claude', label: 'Claude' }
])
expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([
'preflight.detectAgents',
'settings.get'
])
})
it('detects agents through the worktree repo connection for SSH sessions', async () => {
const client = createClient(async (method, params) => {
if (method === 'settings.get') {
return { ok: true, result: { settings: {} } }
}
if (method === 'repo.list') {
return { ok: true, result: { repos: [{ id: 'repo-1', connectionId: 'ssh-1' }] } }
}
if (method === 'preflight.detectRemoteAgents') {
expect(params).toEqual({ connectionId: 'ssh-1' })
return { ok: true, result: ['claude'] }
}
throw new Error(`unexpected request: ${method}`)
})
await expect(
loadOptions({
client,
worktreeId: 'repo-1::/remote/worktree'
})
).resolves.toEqual([{ agent: 'claude', label: 'Claude' }])
expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([
'repo.list',
'settings.get',
'preflight.detectRemoteAgents'
])
})
it('#13752: names another runtime instead of listing the paired host for its workspace', async () => {
const client = createClient(async (method) => {
if (method === 'settings.get') {
return { ok: true, result: { settings: {} } }
}
if (method === 'repo.list') {
return {
ok: true,
result: {
repos: [{ id: 'repo-1', executionHostId: 'runtime:env-b', connectionId: 'b-ssh' }]
}
}
}
throw new Error(`unexpected request: ${method}`)
})
await expect(
loadOptions({ client, worktreeId: 'repo-1::/srv/worktree' })
).rejects.toBeInstanceOf(MobileWorkspaceOnOtherRuntimeError)
expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([
'repo.list',
'settings.get'
])
})
// Put another host’s colliding repo id first so its SSH connection cannot accidentally address this host.
function sharedRepoIdClient(detectAgents: () => unknown) {
return createClient(async (method, params) => {
@@ -444,37 +249,4 @@ describe('mobile new-tab agent loading', () => {
'settings.get'
])
})
it('refreshes like desktop, and detects only where the host predates refresh for phones', async () => {
const client = createClient(async (method) => {
if (method === 'settings.get') {
return { ok: true, result: { settings: {} } }
}
if (method === 'preflight.refreshAgents') {
return {
ok: false,
error: {
code: 'forbidden',
message: "Method 'preflight.refreshAgents' is not available to mobile clients"
}
}
}
if (method === 'preflight.detectAgents') {
return { ok: true, result: ['claude'] }
}
throw new Error(`unexpected request: ${method}`)
})
await expect(
loadOptions({
client,
worktreeId: FLOATING_WORKSPACE_WORKTREE_ID,
refresh: true
})
).resolves.toEqual([{ agent: 'claude', label: 'Claude' }])
expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([
'preflight.refreshAgents',
'settings.get',
'preflight.detectAgents'
])
})
})
@@ -1,111 +0,0 @@
import { createElement, useState, type ReactNode } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, expect, it, vi } from 'vitest'
import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types'
import type { MobileNativeChatController } from './mobile-native-chat-controller-contract'
import { MobileNativeChatOverlay } from './MobileNativeChatOverlay'
import { findByHostType } from '../../test-support/react-test-renderer-host-nodes'
vi.mock('react-native', async () => ({
...(await import('../../test-support/react-native-motion-stub')).reactNativeMotionStub(),
Platform: { OS: 'web' },
StyleSheet: { create: (styles: unknown) => styles, absoluteFillObject: {} },
View: 'View'
}))
vi.mock('react-native-safe-area-context', () => ({
useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
}))
vi.mock('react-native-gesture-handler', () => ({
Gesture: {},
GestureDetector: 'GestureDetector'
}))
vi.mock('./composer/use-mobile-native-chat-composer-tray', () => ({
useMobileNativeChatComposerTray: () => null
}))
vi.mock('./transcript/MobileNativeChatRowOverlaysHost', () => ({
MobileNativeChatRowOverlaysHost: ({ children }: { children: ReactNode }) => children
}))
// Stands in for the chat list: its state lives exactly as long as the mounted view.
vi.mock('./MobileNativeChatView', () => ({
MobileNativeChatView: ({ messages }: { messages: NativeChatMessage[] }) => {
const [mountId] = useState(() => Symbol('chat view'))
return createElement('ChatView', { mountId, ids: messages.map((message) => message.id) })
}
}))
const message = (id: string): NativeChatMessage => ({
id,
role: 'assistant',
blocks: [{ type: 'text', text: `reply ${id}` }],
timestamp: null,
source: 'transcript'
})
function overlay(showNativeChat: boolean, messages: NativeChatMessage[]) {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the overlay reads only these controller members here.
const controller = {
showNativeChat,
nativeChatSession: { messages, status: 'ready' },
nativeChatAgent: 'claude',
nativeChatStructured: false,
nativeChatTurnActive: false,
nativeChatItemSource: null,
nativeChatVisualSource: null,
chatPending: [],
nativeChatQueued: { cards: [], pause: null, sessionKey: 'session' }
} as unknown as MobileNativeChatController
return createElement(MobileNativeChatOverlay, {
controller,
worktreePath: null,
connState: 'connected',
onOpenFile: () => {},
images: {
attachments: [],
isAttaching: false,
attachImage: async () => {},
removeAttachment: () => {},
sendNativeChat: async () => true
},
onMicPress: undefined,
micActive: false,
micStarting: false,
micProcessing: false,
dictationMode: undefined,
onMicPressIn: () => {},
onMicPressOut: () => {},
inputLockReason: null,
sendErrorMessage: null,
onClearSendError: () => {},
sendSurfaceId: 'host\0worktree\0tab',
sessionId: 'session',
getSendCompletionGeneration: () => 0,
keyboardInset: 0,
hostName: null,
onRunInTerminal: () => {}
})
}
let renderer: ReactTestRenderer | null = null
const chatView = () => findByHostType(renderer!.root, 'ChatView').props
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
it('keeps the chat view mounted and hidden while its terminal shows', () => {
const rows = [message('a'), message('b')]
act(() => {
renderer = create(overlay(true, rows))
})
const shown = chatView()
expect(shown.ids).toEqual(['a', 'b'])
// The hidden lane reads as an empty chat; nothing is drawn over the terminal.
act(() => renderer!.update(overlay(false, [])))
expect(renderer!.toJSON()).toBeNull()
act(() => renderer!.update(overlay(true, [...rows, message('c')])))
const back = chatView()
expect(back.mountId).toBe(shown.mountId)
expect(back.ids).toEqual(['a', 'b', 'c'])
})
@@ -1,133 +0,0 @@
// @vitest-environment happy-dom
import { act, useRef } from 'react'
import { createRoot } from 'react-dom/client'
import type * as ReactNative from 'react-native'
import { View, TextInput } from 'react-native'
import { expect, it, vi } from 'vitest'
import { MobileNativeChatLowerRegion } from '../MobileNativeChatLowerRegion.web'
import {
MobileNativeChatComposerAllocation,
useMobileNativeChatComposerAllocation
} from './MobileNativeChatComposerAllocation.web'
import {
MobileNativeChatComposerSuggestions,
type ComposerMenuRow
} from './MobileNativeChatComposerMenu'
vi.mock('react-native', () => vi.importActual<typeof ReactNative>('react-native-web'))
vi.mock(
'./MobileNativeChatComposerAllocation',
() => import('./MobileNativeChatComposerAllocation.web')
)
vi.mock(
'./MobileNativeChatComposerMenuLayer',
() => import('./MobileNativeChatComposerMenuLayer.web')
)
vi.mock('../../../platform/keyboard-occlusion', () => ({ useKeyboardOcclusion: () => 0 }))
vi.mock('lucide-react-native', () => ({
FileText: () => null,
Package: () => null,
Terminal: () => null
}))
const paint = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
for (const population of [10, 100]) {
it(`does no suggestion population work when capacity changes with ${population} results`, async () => {
let capacity = 600
let visits = 0
let fieldMaximum: number | undefined
const rows: ComposerMenuRow[] = Array.from({ length: population }, (_, index) => ({
kind: 'file',
id: `file-${index}`,
get path() {
visits++
return `file-${index}.ts`
}
}))
const container = document.createElement('div')
container.dataset.testid = 'native-chat-view'
document.body.append(container)
const root = createRoot(container)
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
this: HTMLElement
) {
return new DOMRect(0, this === container ? 0 : 100, 300, this === container ? capacity : 100)
})
vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(() => capacity)
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(300)
vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(function (
this: HTMLElement
) {
if (this.dataset.testid === 'native-chat-composer-menu-reservation') {
return Number.parseFloat(this.style.height) || 0
}
if (this.dataset.testid === 'native-chat-composer-group') {
const reserve = this.querySelector<HTMLElement>(
'[data-testid="native-chat-composer-menu-reservation"]'
)
return 160 + (Number.parseFloat(reserve?.style.height ?? '') || 0)
}
return this instanceof HTMLTextAreaElement ? 80 : 100
})
function FieldBudget() {
fieldMaximum = useMobileNativeChatComposerAllocation()?.fieldMaxHeight
return null
}
function Composer({ items }: { items: ComposerMenuRow[] }) {
const anchor = useRef<View>(null)
const field = useRef<TextInput>(null)
return (
<MobileNativeChatComposerAllocation anchorRef={anchor} fieldRef={field} hasMenu>
<View ref={anchor} testID="native-chat-composer-group">
<MobileNativeChatComposerSuggestions
anchorRef={anchor}
rows={items}
onPick={() => {}}
/>
<TextInput ref={field} multiline defaultValue="@file" />
<FieldBudget />
</View>
</MobileNativeChatComposerAllocation>
)
}
const render = (items: ComposerMenuRow[]) => (
<MobileNativeChatLowerRegion>
<Composer items={items} />
</MobileNativeChatLowerRegion>
)
try {
await act(async () => root.render(render(rows)))
await act(async () => container.querySelector('textarea')!.focus())
await act(paint)
expect(
container.querySelector('[aria-label="file-0.ts"]'),
JSON.stringify({
focus: document.activeElement?.tagName,
fieldMaximum,
html: container.innerHTML.slice(-1800)
})
).not.toBeNull()
const prior = fieldMaximum
expect(prior).toBeGreaterThan(0)
visits = 0
await act(async () => {
capacity = 420
window.dispatchEvent(new Event('resize'))
await paint()
})
await act(paint)
expect(fieldMaximum).toBeLessThan(prior!)
expect(visits).toBe(0)
await act(async () =>
root.render(render([...rows, { kind: 'file', id: 'new', path: 'new-file.ts' }]))
)
expect(visits).toBeGreaterThan(0)
expect(container.querySelector('[aria-label="new-file.ts"]')).not.toBeNull()
} finally {
await act(async () => root.unmount())
container.remove()
vi.restoreAllMocks()
}
})
}
@@ -1,105 +0,0 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { createRoot } from 'react-dom/client'
import type * as ReactNative from 'react-native'
import { expect, it, vi } from 'vitest'
import { MobileNativeChatLowerRegion } from '../MobileNativeChatLowerRegion.web'
import { MobileNativeChatPromptCard } from './MobileNativeChatPromptCard'
vi.mock('react-native', () => vi.importActual<typeof ReactNative>('react-native-web'))
vi.mock('lucide-react-native', () => ({}))
vi.mock('./MobileNativeChatAsk', () => ({ MobileNativeChatAsk: () => null }))
vi.mock('./MobileNativeChatPermission', () => ({ MobileNativeChatPermission: () => null }))
vi.mock('./MobileNativeChatStructuredAsk', () => ({ MobileNativeChatStructuredAsk: () => null }))
vi.mock('./MobileNativeChatPromptStrip', () => ({ MobileNativeChatPromptStrip: () => null }))
vi.mock('../../../platform/use-reduced-motion', () => ({ useReducedMotionEnabled: () => true }))
vi.mock('./MobileNativeChatQuestion', () => ({
MobileNativeChatQuestion: () => <button>Pending question</button>
}))
it('reveals a question already pending when the lower region mounts', async () => {
const observers = new Set<ResizeObserver>()
const deliver = new Map<ResizeObserver, () => void>()
class LayoutObserver implements ResizeObserver {
private nodes = new Set<Element>()
constructor(callback: ResizeObserverCallback) {
observers.add(this)
deliver.set(this, () =>
callback(
Array.from(this.nodes, (target): ResizeObserverEntry => ({
target,
contentRect: target.getBoundingClientRect(),
borderBoxSize: [],
contentBoxSize: [],
devicePixelContentBoxSize: []
})),
this
)
)
}
observe(node: Element) {
this.nodes.add(node)
}
unobserve(node: Element) {
this.nodes.delete(node)
}
disconnect() {
this.nodes.clear()
}
}
vi.stubGlobal('ResizeObserver', LayoutObserver)
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
this: HTMLElement
) {
return new DOMRect(0, 0, 300, this.dataset.testid === 'native-chat-view' ? 600 : 200)
})
vi.useFakeTimers()
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const hidden = () => {
for (
let node: HTMLElement | null = container.querySelector('button');
node;
node = node.parentElement
) {
if (getComputedStyle(node).opacity === '0') {
return true
}
}
return false
}
try {
await act(async () =>
root.render(
<div data-testid="native-chat-view">
<MobileNativeChatLowerRegion>
<MobileNativeChatPromptCard
question={{
question: 'Continue?',
options: [],
optionTokens: [],
multiSelect: false
}}
/>
</MobileNativeChatLowerRegion>
</div>
)
)
expect(container.querySelector('button')).not.toBeNull()
expect(hidden()).toBe(true)
await act(async () => {
for (const observer of observers) {
deliver.get(observer)?.()
}
await vi.advanceTimersByTimeAsync(500)
})
expect(hidden()).toBe(false)
} finally {
await act(async () => root.unmount())
container.remove()
vi.useRealTimers()
vi.restoreAllMocks()
vi.unstubAllGlobals()
}
})
@@ -1,422 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { connectMobileNativeChatLowerScroll } from './mobile-native-chat-lower-scroll'
let root: HTMLDivElement
let viewport: HTMLDivElement
let content: HTMLDivElement
let anchor: HTMLParagraphElement
let field: HTMLTextAreaElement
let group: HTMLDivElement
let viewportHeight: number
let extent: number
let addedAbove: number
let addedBeforeField: number
let connection: ReturnType<typeof connectMobileNativeChatLowerScroll> | undefined
const painted = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
beforeEach(() => {
viewportHeight = 100
extent = 350
addedAbove = 0
addedBeforeField = 0
root = document.createElement('div')
root.dataset.testid = 'native-chat-view'
viewport = document.createElement('div')
content = document.createElement('div')
anchor = document.createElement('p')
group = document.createElement('div')
group.dataset.testid = 'native-chat-composer-group'
field = document.createElement('textarea')
field.value = 'A separate retained draft'
group.append(field)
content.append(anchor, group)
viewport.append(content)
root.append(viewport)
document.body.append(root)
vi.spyOn(root, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, 0, 300, 600))
vi.spyOn(viewport, 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, 0, 300, viewportHeight)
)
Object.defineProperties(viewport, {
clientHeight: { get: () => viewportHeight },
clientWidth: { value: 300 },
scrollHeight: { get: () => extent + addedAbove + addedBeforeField }
})
vi.spyOn(content, 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, -viewport.scrollTop, 300, extent + addedAbove + addedBeforeField)
)
vi.spyOn(anchor, 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, addedAbove - viewport.scrollTop, 300, 200)
)
vi.spyOn(group, 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, 220 + addedAbove + addedBeforeField - viewport.scrollTop, 300, 130)
)
vi.spyOn(field, 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, 260 + addedAbove + addedBeforeField - viewport.scrollTop, 300, 30)
)
vi.spyOn(document, 'elementFromPoint').mockImplementation(() => {
const rect = anchor.getBoundingClientRect()
return rect.top <= 4 && rect.bottom > 4 ? anchor : null
})
})
afterEach(() => {
connection?.dispose()
connection = undefined
root.remove()
vi.useRealTimers()
vi.restoreAllMocks()
})
function connect() {
connection = connectMobileNativeChatLowerScroll(viewport, content, () => {})
return connection
}
function userScroll(offset: number) {
viewport.dispatchEvent(new WheelEvent('wheel'))
viewport.scrollTop = offset
viewport.dispatchEvent(new Event('scroll'))
viewport.dispatchEvent(new Event('scrollend'))
}
it('starts at the bottom and keeps newly inserted lower content reachable while attached', async () => {
const lower = connect()
await painted()
expect(viewport.scrollTop).toBe(250)
addedAbove = 80
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(330)
})
it('reveals the focused editor after an inline menu appears without another focus event', async () => {
const lower = connect()
field.focus()
await painted()
expect(viewport.scrollTop).toBe(190)
addedBeforeField = 20
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(210)
addedAbove = 80
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(290)
expect(document.activeElement).toBe(field)
expect(field.value).toBe('A separate retained draft')
})
it('holds the visible content after deliberate scrolling and drops a removed anchor', async () => {
const lower = connect()
field.focus()
await painted()
userScroll(140)
await painted()
addedAbove = 80
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(220)
expect(anchor.getBoundingClientRect().top).toBe(-140)
anchor.remove()
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(220)
expect(document.activeElement).toBe(field)
addedAbove = 120
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(220)
})
it('lets deliberate scrolling cancel a pending field reveal across an unrelated layout', async () => {
const lower = connect()
field.focus()
await painted()
lower.reveal(group)
userScroll(130)
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(130)
expect(document.activeElement).toBe(field)
})
it('defers anchor correction through canceled touch pointers until every contact ends', async () => {
const lower = connect()
await painted()
const touched = document.createElement('div')
content.append(touched)
const touch = (type: string, count: number) => {
const event = new TouchEvent(type, {
bubbles: true,
touches: Array.from(
{ length: count },
(_, identifier) => new Touch({ identifier, target: touched })
)
})
touched.dispatchEvent(event)
}
vi.useFakeTimers()
touch('touchstart', 2)
viewport.scrollTop = 140
viewport.dispatchEvent(new Event('scroll'))
const canceled = new Event('pointercancel', { bubbles: true })
Object.defineProperty(canceled, 'pointerType', { value: 'touch' })
viewport.dispatchEvent(canceled)
addedAbove = 80
lower.layoutChanged()
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(140)
viewport.scrollTop = 130
lower.layoutChanged()
await vi.advanceTimersByTimeAsync(20)
viewport.dispatchEvent(new Event('scroll'))
touch('touchend', 1)
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(130)
touched.remove()
touch('touchend', 0)
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(210)
lower.layoutChanged()
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(210)
})
it('carries a correction into a new visible anchor before a later insertion', async () => {
extent = 550
const next = document.createElement('p')
content.append(next)
vi.spyOn(next, 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, 200 + addedAbove + addedBeforeField - viewport.scrollTop, 300, 180)
)
const lower = connect()
await painted()
userScroll(140)
await painted()
vi.useFakeTimers()
viewport.dispatchEvent(
new PointerEvent('pointerdown', { pointerType: 'touch', pointerId: 1, bubbles: true })
)
addedAbove = 80
lower.layoutChanged()
await vi.advanceTimersByTimeAsync(20)
vi.mocked(document.elementFromPoint).mockReturnValue(next)
viewport.scrollTop = 280
viewport.dispatchEvent(new Event('scroll'))
anchor.remove()
addedBeforeField = 40
lower.layoutChanged()
document.dispatchEvent(new PointerEvent('pointerup', { pointerType: 'touch', pointerId: 1 }))
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(400)
expect(next.getBoundingClientRect().top).toBe(-80)
lower.layoutChanged()
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(400)
})
it('preserves outer layout displacement without undoing a nested scroll', async () => {
const inner = document.createElement('div')
content.prepend(inner)
inner.append(anchor)
vi.mocked(anchor.getBoundingClientRect).mockImplementation(
() => new DOMRect(0, addedAbove - viewport.scrollTop - inner.scrollTop, 300, 200)
)
const lower = connect()
await painted()
userScroll(140)
await painted()
vi.useFakeTimers()
viewport.dispatchEvent(
new PointerEvent('pointerdown', { pointerType: 'touch', pointerId: 2, bubbles: true })
)
addedAbove = 80
lower.layoutChanged()
inner.scrollTop = 30
inner.dispatchEvent(new Event('scroll'))
document.dispatchEvent(new PointerEvent('pointerup', { pointerType: 'touch', pointerId: 2 }))
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(220)
expect(inner.scrollTop).toBe(30)
expect(anchor.getBoundingClientRect().top).toBe(-170)
})
it('retires an unreachable correction after native range clamping without attaching', async () => {
extent = 550
group.remove()
vi.mocked(anchor.getBoundingClientRect).mockImplementation(
() => new DOMRect(0, 140 + addedAbove - viewport.scrollTop, 300, 20)
)
const lower = connect()
await painted()
userScroll(140)
await painted()
addedAbove = 40
extent = 160
viewport.scrollTop = 100
viewport.dispatchEvent(new Event('scroll'))
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(100)
extent = 550
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(100)
addedAbove = 80
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(140)
})
it('preserves user navigation through a rubber-band excursion without writing against the bounce', async () => {
const lower = connect()
await painted()
userScroll(0)
await painted()
viewport.dispatchEvent(new WheelEvent('wheel'))
viewport.scrollTop = -20
viewport.dispatchEvent(new Event('scroll'))
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(-20)
viewport.scrollTop = 15
viewport.dispatchEvent(new Event('scroll'))
viewport.dispatchEvent(new Event('scrollend'))
await painted()
expect(viewport.scrollTop).toBe(15)
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(15)
userScroll(250)
await painted()
viewport.dispatchEvent(new WheelEvent('wheel'))
viewport.scrollTop = 270
viewport.dispatchEvent(new Event('scroll'))
viewport.scrollTop = 230
viewport.dispatchEvent(new Event('scroll'))
viewport.dispatchEvent(new Event('scrollend'))
await painted()
expect(viewport.scrollTop).toBe(230)
})
it('reveals a fitting composer surface through menu entry and removal despite incidental movement', async () => {
viewportHeight = 219
extent = 900
const inset = document.createElement('div')
inset.dataset.testid = 'native-chat-composer-inset'
group.append(inset)
inset.append(field)
vi.mocked(group.getBoundingClientRect).mockImplementation(
() => new DOMRect(0, -viewport.scrollTop, 300, 900)
)
vi.spyOn(inset, 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, 634 + addedBeforeField - viewport.scrollTop, 300, 214)
)
vi.mocked(field.getBoundingClientRect).mockImplementation(
() => new DOMRect(0, 653 + addedBeforeField - viewport.scrollTop, 300, 128)
)
const lower = connect()
field.focus()
await painted()
userScroll(637)
await painted()
expect(inset.getBoundingClientRect().top).toBe(-3)
addedBeforeField = 301
lower.reveal(group, 'menu')
viewport.scrollTop = 938
viewport.dispatchEvent(new Event('scroll'))
lower.layoutChanged()
await painted()
expect(inset.getBoundingClientRect().top).toBe(5)
expect(inset.getBoundingClientRect().bottom).toBe(219)
addedBeforeField = 0
lower.reveal(group, 'edit')
viewport.scrollTop = 594
field.scrollTop = 30
field.dispatchEvent(new Event('scroll', { bubbles: true }))
viewport.dispatchEvent(new Event('scroll'))
await painted()
expect(inset.getBoundingClientRect().top).toBe(5)
expect(inset.getBoundingClientRect().bottom).toBe(219)
expect(field.scrollTop).toBe(30)
expect(document.activeElement).toBe(field)
expect(field.value).toBe('A separate retained draft')
})
it('keeps a deliberately offscreen field offscreen when its fitting frame still intersects', async () => {
viewportHeight = 219
extent = 900
const inset = document.createElement('div')
inset.dataset.testid = 'native-chat-composer-inset'
group.append(inset)
inset.append(field)
vi.mocked(group.getBoundingClientRect).mockImplementation(
() => new DOMRect(0, -viewport.scrollTop, 300, 900)
)
vi.spyOn(inset, 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, 634 + addedBeforeField - viewport.scrollTop, 300, 214)
)
vi.mocked(field.getBoundingClientRect).mockImplementation(
() => new DOMRect(0, 653 + addedBeforeField - viewport.scrollTop, 300, 128)
)
const lower = connect()
field.focus()
await painted()
userScroll(429)
await painted()
expect(inset.getBoundingClientRect().top).toBe(205)
expect(field.getBoundingClientRect().top).toBe(224)
addedBeforeField = 40
lower.layoutChanged()
await painted()
expect(viewport.scrollTop).toBe(429)
expect(document.activeElement).toBe(field)
expect(field.value).toBe('A separate retained draft')
field.dispatchEvent(new Event('input', { bubbles: true }))
await painted()
expect(inset.getBoundingClientRect().top).toBe(5)
expect(inset.getBoundingClientRect().bottom).toBe(219)
})
it('keeps new Tab and tap focus reveals while later navigation cancels and editing keys do not', async () => {
const lower = connect()
vi.useFakeTimers()
field.focus()
await vi.advanceTimersByTimeAsync(20)
field.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', bubbles: true }))
field.blur()
field.focus()
viewport.scrollTop = 0
viewport.dispatchEvent(new Event('scroll'))
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(190)
field.blur()
field.dispatchEvent(
new PointerEvent('pointerdown', { pointerType: 'mouse', pointerId: 3, bubbles: true })
)
field.focus()
viewport.scrollTop = 0
viewport.dispatchEvent(new Event('scroll'))
field.dispatchEvent(
new PointerEvent('pointermove', { pointerType: 'mouse', pointerId: 3, bubbles: true })
)
document.dispatchEvent(new PointerEvent('pointerup', { pointerType: 'mouse', pointerId: 3 }))
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(190)
lower.reveal(group, 'edit')
field.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }))
viewport.scrollTop = 0
viewport.dispatchEvent(new Event('scroll'))
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(190)
lower.reveal(group)
group.dispatchEvent(new KeyboardEvent('keydown', { key: 'PageUp', bubbles: true }))
viewport.scrollTop = 130
viewport.dispatchEvent(new Event('scroll'))
viewport.dispatchEvent(new Event('scrollend'))
await vi.advanceTimersByTimeAsync(200)
expect(viewport.scrollTop).toBe(130)
})
@@ -4,19 +4,12 @@ import type {
AgentJournalSubmission
} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types'
import { withStopRowsAfterStoppedSends } from '../../../../../src/shared/native-chat/native-chat-stopped-before-start'
import { createElement } from 'react'
import { act, create } from 'react-test-renderer'
import { expect, it } from 'vitest'
import type {
NativeChatBlock,
NativeChatMessage
} from '../../../../../src/shared/native-chat/native-chat-types'
import { nativeChatTaskListPredecessors } from '../../../../../src/shared/native-chat/input/native-chat-task-list-history'
import { nativeChatDockedTaskList } from '../../../../../src/shared/native-chat/input/native-chat-task-list-state'
import { projectMobileNativeChatMessages } from './mobile-native-chat-projection'
import { useMobileNativeChatProjection } from './use-mobile-native-chat-projection'
import { useMobileNativeChatTransientData } from './use-mobile-native-chat-transient-data'
import { useMobileNativeChatTurnDisclosure } from './use-mobile-native-chat-turn-disclosure'
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
function row(
@@ -231,126 +224,6 @@ it('forgets evicted tool contributions and releases generated orphan names', ()
expect(state.rows[1]?.blocks).toEqual([result('unknown')])
})
it('places a surviving roster at its new first sibling and recomputes labels', () => {
const sibling = (id: string) =>
row(id, 'system', [
{
type: 'subagent',
id,
groupId: 'group',
label: 'Audit',
state: 'completed'
}
])
const first = sibling('one'),
second = sibling('two'),
third = sibling('three')
const middle = prose('middle', 'Between', 'user')
let state = projectMobileNativeChatMessages([first, middle, second, third], 'claude')
state = projectMobileNativeChatMessages([middle, second, third], 'claude', state)
expect(state.rows.map((message) => message.id)).toEqual(['middle', 'two'])
expect(state.rows[1]?.blocks).toEqual([
{
type: 'subagent-group',
groupId: 'group',
agents: [
{ id: 'two', label: 'Audit', state: 'completed' },
{ id: 'three', label: 'Audit 2', state: 'completed' }
]
}
])
})
it('updates live tools, reasoning, sibling outcomes and waiting rows through the phone hooks', () => {
let live = [
prose('user', 'Inspect', 'user'),
prose('a', 'Checking'),
spawn('s1'),
spawn('s2'),
row('tool', 'assistant', [call('live')]),
{ ...prose('child', 'Child'), agentId: 'child' }
]
const held = { ...prose('held', 'Follow-up', 'user'), queued: true as const }
let current = [...live, held]
let output: readonly NativeChatMessage[] = []
let scope = 'chat'
const pending = [{ id: 'pending', text: 'Pending', images: ['preview'] }]
function Transcript() {
const folded = useMobileNativeChatProjection(current, 'claude', [scope])
output = useMobileNativeChatTransientData(
{
folded,
streaming: null,
pending
},
scope
)
useMobileNativeChatTurnDisclosure({
messages: output,
enabled: true,
isWorking: false,
scopeKey: scope
})
nativeChatTaskListPredecessors(output)
nativeChatDockedTaskList(folded)
return null
}
let renderer: ReturnType<typeof create>
act(() => {
renderer = create(createElement(Transcript))
})
live = [
prose('user', 'Inspect', 'user'),
prose('a', 'Checking now'),
spawn('s1'),
spawn('s2', 'completed'),
row('tool', 'assistant', [call('live', 'completed'), result('live')]),
{ ...prose('child', 'Child revised'), agentId: 'child' },
{ ...prose('thought', 'Consider', 'reasoning'), state: 'completed', completedAt: 10 }
]
current = [...live, { ...held }]
act(() => renderer.update(createElement(Transcript)))
expect(output.map((message) => message.id)).toEqual([
'user',
'a',
's1',
'thought',
'held',
'pending'
])
expect(output[1]?.blocks).toEqual([
{ type: 'text', text: 'Checking now' },
call('live', 'completed'),
result('live')
])
expect(output[2]?.blocks).toEqual([
{
type: 'subagent-group',
groupId: 'live-group',
agents: [
{ id: 's1', label: 's1', state: 'working' },
{ id: 's2', label: 's2', state: 'completed' }
]
}
])
expect(output[3]).toMatchObject({
role: 'reasoning',
state: 'completed',
completedAt: 10,
blocks: [{ type: 'text', text: 'Consider' }]
})
expect(output[4]?.queued).toBe(true)
expect(output[5]?.blocks).toEqual([
{ type: 'text', text: 'Pending' },
{ type: 'image-ref', url: 'preview' }
])
scope = 'another-chat'
current = [prose('new', 'New chat')]
act(() => renderer.update(createElement(Transcript)))
expect(output.map((message) => message.id)).toEqual(['new', 'pending'])
act(() => renderer.unmount())
})
it('preserves current delivery facts and synthetic notices when upstream wrappers refresh', () => {
const items: AgentJournalRenderItem[] = [
{
@@ -407,32 +280,3 @@ it('preserves current delivery facts and synthetic notices when upstream wrapper
expect(state.rows[1]?.role).toBe('system')
expect(state.rows[2]?.blocks).toEqual([{ type: 'text', text: 'Done' }])
})
it('projects each streamed tail replacement or append as a fresh projection would', () => {
const sibling = (id: string) =>
row(id, 'system', [{ type: 'subagent', id, groupId: 'g', label: 'Audit', state: 'working' }])
const tail = [
prose('tail', 'Reading'),
prose('tail', 'Reading the file'),
row('tail', 'assistant', [call('read')])
]
const appended = [
prose('ask', 'Go on', 'user'),
row('tools', 'assistant', [call('x'), result('x'), result('missing')]),
prose('unpaired-tool-results:["tools",1]', 'Later', 'user'),
prose('image', '[Image: source: /tmp/a.png]', 'user'),
prose('prompt', '[Image #1] why', 'user'),
sibling('one'),
sibling('two')
]
let input = [prose('unpaired-tool-results:["tools",0]', 'Reserved', 'user'), prose('lead', 'Hi')]
const stream = [
...tail.map((message) => (input = [...input.slice(0, 2), message])),
...appended.map((message) => (input = [...input, message]))
]
let state = projectMobileNativeChatMessages([], 'claude')
for (const step of stream) {
state = projectMobileNativeChatMessages(step, 'claude', state)
expect(state.rows).toEqual(projectMobileNativeChatMessages(step, 'claude').rows)
}
})
@@ -1,76 +0,0 @@
import { readFileSync } from 'node:fs'
import { expect, it } from 'vitest'
import { projectStructuredItemToNativeChat } from '@orca/test-host/shared/agent-session/view/structured-agent-session-projection'
import {
createNativeChatMerger,
applyAppend
} from '@orca/test-host/shared/native-chat/native-chat-merge'
import { decodeClaudeTranscriptLine } from '@orca/test-host/main/native-chat/transcript-line-decoders-claude'
import { readCodexThreadItem } from '@orca/test-host/main/codex/structured/items/codex-thread-item-identity'
import { codexJournalItem } from '@orca/test-host/main/codex/structured/items/codex-structured-item-translation'
import { projectMobileNativeChatMessages } from '@orca/test-mobile/session/native-chat/transcript/mobile-native-chat-projection'
it('preserves captured agent output through legacy appends', () => {
const claude = readFileSync(
new URL(
'../../../../../src/main/claude/__fixtures__/claude-adapter-capture-fold.jsonl',
import.meta.url
),
'utf8'
)
.trim()
.split('\n')
.flatMap((line, index) => {
const record = JSON.parse(line)
const message = record.frame
? decodeClaudeTranscriptLine(JSON.stringify(record.frame), `capture-${index}`)
: null
return message ? [message] : []
})
const codex = readFileSync(
new URL(
'../../../../../src/main/codex/__fixtures__/codex-hook-outcomes.jsonl',
import.meta.url
),
'utf8'
)
.trim()
.split('\n')
.flatMap((line, index) => {
const parsed = JSON.parse(line)
const frame = parsed.frame ?? parsed
const item =
frame?.method === 'item/completed' ? readCodexThreadItem(frame.params?.item) : null
const body = item ? codexJournalItem(item).body : null
const message = body
? projectStructuredItemToNativeChat({
itemId: `capture-${index}`,
sequence: index,
revision: 1,
observedAt: index,
body
})
: null
return message ? [message] : []
})
for (const [agent, records] of [
['claude', claude],
['codex', codex]
] as const) {
const merger = createNativeChatMerger()
let state = projectMobileNativeChatMessages([], agent)
for (const message of records) {
const input = applyAppend(merger, [message])
state = projectMobileNativeChatMessages(input, agent, state)
}
expect(state.rows.at(-1)?.blocks).toEqual([
{
type: 'text',
text:
agent === 'claude'
? 'FIRST DONE banana'
: 'The command was blocked by an automatic hook stating “Deploys are frozen,” so it printed nothing.'
}
])
}
})
@@ -122,22 +122,6 @@ afterEach(() => {
})
describe('useMobileNewTabAgentOptions', () => {
it('lists the agents on the first "+" open after the session loads them', async () => {
const host: FakeHost = { agents: () => claude }
const client = createClient(host)
const drawer = mountDrawer(queryClient)
await drawer.render({ client, open: false, prefetch: true })
host.agents = () => new Promise<RpcResponse>(() => {})
drawer.states.length = 0
await drawer.render({ client, open: true, prefetch: true })
expect(drawer.states).not.toContain('loading')
expect(drawer.state()).toBe('loaded')
expect(drawer.options()).toEqual([{ agent: 'claude', label: 'Claude' }])
drawer.unmount()
})
it('#21856: reopening the drawer shows the last agents at once and reads settings again', async () => {
const host: FakeHost = { agents: () => ({ id: '1', ok: true, result: ['claude', 'codex'] }) }
const client = createClient(host)
@@ -159,30 +143,6 @@ describe('useMobileNewTabAgentOptions', () => {
drawer.unmount()
})
it('reads the agents again on the next open after a failed read', async () => {
const host: FakeHost = {
agents: () => ({
id: '1',
ok: false,
error: { code: 'runtime_error', message: 'boom' },
_meta: { runtimeId: 'r' }
})
}
const client = createClient(host)
const drawer = mountDrawer(queryClient)
await drawer.render({ client, open: false, prefetch: true })
await drawer.render({ client, open: true, prefetch: true })
expect(drawer.state()).toBe('error')
host.agents = () => claude
await drawer.render({ client, open: false, prefetch: true })
await drawer.render({ client, open: true, prefetch: true })
expect(drawer.state()).toBe('loaded')
expect(drawer.options()).toEqual([{ agent: 'claude', label: 'Claude' }])
drawer.unmount()
})
it("does not offer one relayed server's agents for another's workspace with the same id", async () => {
const drawer = mountDrawer(queryClient)
const answered = createClient({ agents: () => claude })
@@ -1,64 +0,0 @@
import { act } from 'react-test-renderer'
import { focusManager } from '@tanstack/react-query'
import { afterEach, expect, it } from 'vitest'
import { rpcSuccess } from '../mobile-web-shell/bridge-host-test-fakes'
import { hookMount, settleQueryNotifications } from '../test-support/rpc-recording/hook-mount'
import { stubRpcClient } from '../transport/rpc-client-test-stub'
import { useMobileSourceControlSettings } from './mobile-source-control-settings'
let screen: ReturnType<typeof hookMount> | null = null
afterEach(async () => {
await screen?.unmount()
screen = null
focusManager.setFocused(undefined)
})
// Starts away from desktop's defaults so the first read shows it landed.
function mountSettingsReader() {
let diffShowWhitespace = true
const seen: { diffShowWhitespace?: boolean } = {}
const client = stubRpcClient({
sendRequest: async () => rpcSuccess('1', { settings: { diffShowWhitespace } })
})
screen = hookMount(() => {
seen.diffShowWhitespace = useMobileSourceControlSettings(
'host-1',
client,
'connected'
).settings.diffShowWhitespace
})
return {
screen,
seen,
hideWhitespaceOnDesktop: () => {
diffShowWhitespace = false
}
}
}
it('shows a setting changed on the desktop when a screen opens again', async () => {
const reader = mountSettingsReader()
reader.screen.mount()
await settleQueryNotifications()
expect(reader.seen.diffShowWhitespace).toBe(true)
reader.screen.leave()
reader.hideWhitespaceOnDesktop()
reader.screen.mount()
await settleQueryNotifications()
expect(reader.seen.diffShowWhitespace).toBe(false)
})
it('shows a setting changed on the desktop when the app comes back to the foreground', async () => {
const reader = mountSettingsReader()
reader.screen.mount()
await settleQueryNotifications()
expect(reader.seen.diffShowWhitespace).toBe(true)
reader.hideWhitespaceOnDesktop()
act(() => focusManager.setFocused(false))
act(() => focusManager.setFocused(true))
await settleQueryNotifications()
expect(reader.seen.diffShowWhitespace).toBe(false)
})
@@ -1,105 +0,0 @@
import { createElement, useEffect } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { expect, it, vi } from 'vitest'
import { createFakeRpcClient, rpcSuccess } from '../mobile-web-shell/bridge-host-test-fakes'
import {
documentQueryClient,
settleQueryNotifications
} from '../test-support/rpc-recording/hook-mount'
import { useMobileSourceControlLoaders } from './use-mobile-source-control-loaders'
import { useMobileDiffReviewSnapshot } from '../session/use-mobile-diff-review-snapshot'
const focus = vi.hoisted(() => ({ current: true }))
vi.mock('expo-router', () => ({
useFocusEffect: (effect: () => (() => void) | void) =>
useEffect(() => (focus.current ? effect() : undefined), [effect, focus.current])
}))
vi.mock('lucide-react-native', () => ({
ArrowDown: 'ArrowDown',
ArrowDownUp: 'ArrowDownUp',
ArrowUp: 'ArrowUp',
Check: 'Check',
CloudUpload: 'CloudUpload',
GitBranch: 'GitBranch',
GitPullRequestArrow: 'GitPullRequestArrow',
History: 'History',
RefreshCw: 'RefreshCw'
}))
it('shows what Review staged when returning to Changes without remounting the screen', async () => {
const client = createFakeRpcClient()
const clearError = () => {}
let tree: ReactTestRenderer | null = null
const read: {
loaders: ReturnType<typeof useMobileSourceControlLoaders> | null
review: ReturnType<typeof useMobileDiffReviewSnapshot> | null
} = { loaders: null, review: null }
const queries = documentQueryClient()
const screen = (reviewOpen = false) => queries.wrap(createElement(Screen, { reviewOpen }))
function Screen({ reviewOpen }: { reviewOpen: boolean }) {
read.loaders = useMobileSourceControlLoaders({
hostId: 'host',
client,
connState: 'connected',
statusIdentityKey: 'host:wt',
worktreeId: 'wt',
setActionError: clearError
})
return reviewOpen ? createElement(Review) : null
}
function Review() {
read.review = useMobileDiffReviewSnapshot({
client,
connState: 'connected',
hostId: 'host',
worktreeId: 'wt',
commitOid: null,
filter: 'unstaged',
setActionError: clearError
})
return null
}
async function resolveStatus(area: string) {
const request = client.requests.findLast((request) => request.method === 'git.status')
if (!request) {
throw new Error('Expected status refresh')
}
await act(async () =>
request.resolve(
rpcSuccess('status', { entries: [{ path: 'app.ts', status: 'modified', area }] })
)
)
await settleQueryNotifications()
}
try {
await act(async () => {
tree = create(screen())
})
await resolveStatus('unstaged')
expect(read.loaders?.screenState).toMatchObject({
kind: 'ready',
status: { entries: [{ area: 'unstaged' }] }
})
focus.current = false
await act(async () => {
tree?.update(screen(true))
})
// Review's read after its stage lands in the entry Changes shows.
await act(async () => {
void read.review?.loadReviewData()
})
await resolveStatus('staged')
focus.current = true
await act(async () => {
tree?.update(screen())
})
expect(read.loaders?.screenState).toMatchObject({
kind: 'ready',
status: { entries: [{ area: 'staged' }] }
})
} finally {
await act(async () => {
tree?.unmount()
})
}
})
@@ -81,70 +81,9 @@ function drain(queue: WriteQueueHarness): void {
}
describe('terminal WebView write queue', () => {
// Use distinct chunk strings so retained-code-unit counts detect actual queue retention.
function distinctChunks(count: number, codeUnits: number): string[] {
return Array.from({ length: count }, (_v, i) => {
const marker = `chunk-${i}:`
return marker + String.fromCharCode(0x61 + (i % 26)).repeat(codeUnits - marker.length)
})
}
// Count queue-reachable string units, not heap bytes; xterm may still retain submitted chunks.
it('retains only the pending chunk after 127 of 128 dequeues', () => {
const CHUNK_CODE_UNITS = 65_536
const CHUNK_COUNT = 128
const chunks = distinctChunks(CHUNK_COUNT, CHUNK_CODE_UNITS)
const measure = (): number => {
const queue = createWriteQueue()
for (const chunk of chunks) {
queue.enqueue(chunk)
}
for (let i = 0; i < CHUNK_COUNT - 1; i++) {
queue.next()
}
return queue.queuedCodeUnits()
}
expect(measure()).toBe(CHUNK_CODE_UNITS)
})
// Legacy compaction retention grows with backlog because it waits for consumed slots to exceed half the queue.
it.each([
[1_000, 500],
[10_000, 5_000]
])('at backlog %i the head reaches %i before any compaction', (backlog, dequeues) => {
const chunks = distinctChunks(backlog, 64)
const measure = (): { codeUnits: number; head: number; slots: number } => {
const queue = createWriteQueue()
for (const chunk of chunks) {
queue.enqueue(chunk)
}
for (let i = 0; i < dequeues; i++) {
queue.next()
}
const { head, slots } = queue.snapshot()
return { codeUnits: queue.queuedCodeUnits(), head, slots: slots.length }
}
const shipped = measure()
// Reachability drops even before compaction.
expect(shipped.head).toBe(dequeues)
expect(shipped.slots).toBe(backlog)
// Only pending string contents remain reachable from the queue.
expect(shipped.codeUnits).toBe((backlog - dequeues) * 64)
})
it('joins queued strings up to a boundary into one write', () => {
const queue = createWriteQueue()
queue.enqueue('a')
queue.enqueue('b')
queue.enqueue('c')
queue.enqueueBoundary(() => {})
queue.enqueue('d')
drain(queue)
expect(queue.writes).toEqual(['abc', 'd'])
})
it('hands xterm a 100 KB write as ordered slices of at most 16 KB', () => {
const queue = createWriteQueue()
@@ -178,20 +117,6 @@ describe('terminal WebView write queue', () => {
expect(order).toEqual(['boundary', 'drained'])
})
it('submits callback-only and empty writes', () => {
const queue = createWriteQueue()
const calls: string[] = []
queue.enqueueBoundary(() => calls.push('first'))
queue.enqueue('')
queue.enqueueBoundary(() => calls.push('second'))
queue.enqueue('')
drain(queue)
expect(calls).toEqual(['first', 'second'])
expect(queue.writes).toEqual(['', ''])
expect(queue.snapshot()).toEqual({ slots: [], head: 0 })
})
it('discards pending writes after a reset mid-flight', () => {
const queue = createWriteQueue()
queue.enqueue('first')
@@ -226,32 +151,4 @@ describe('terminal WebView write queue', () => {
expect(queue.writes).toEqual(['first', 'secondreentrant'])
})
it('compacts consumed slots and keeps order', () => {
const queue = createWriteQueue()
const total = 200
const consumed = 129
for (let i = 0; i < total; i++) {
queue.enqueue(`chunk-${i}`)
}
const taken: unknown[] = []
for (let i = 0; i < consumed; i++) {
taken.push(queue.next())
}
expect(taken).toEqual(Array.from({ length: consumed }, (_v, i) => `chunk-${i}`))
const { slots, head } = queue.snapshot()
expect(head).toBe(0)
expect(slots).toEqual(
Array.from({ length: total - consumed }, (_v, i) => `chunk-${consumed + i}`)
)
})
it('resets once the queue is fully consumed', () => {
const queue = createWriteQueue()
queue.enqueue('only')
expect(queue.next()).toBe('only')
expect(queue.next()).toBeUndefined()
expect(queue.snapshot()).toEqual({ slots: [], head: 0 })
})
})
@@ -1,71 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const storage = vi.hoisted(() => new Map<string, string>())
const network = vi.hoisted(() => ({ type: 'WIFI', ip: '192.168.1.23' }))
vi.mock('@react-native-async-storage/async-storage', () => ({
default: {
getItem: async (key: string) => storage.get(key) ?? null,
setItem: async (key: string, value: string) => void storage.set(key, value)
}
}))
vi.mock('expo-network', () => ({
NetworkStateType: { NONE: 'NONE', UNKNOWN: 'UNKNOWN', CELLULAR: 'CELLULAR' },
getNetworkStateAsync: async () => ({ type: network.type, isConnected: true }),
getIpAddressAsync: async () => network.ip
}))
import { lastGoodPathWasDirectHere, recordHostGoodPath } from './host-path-memory'
function joinNetwork(type: string, ip: string): void {
network.type = type
network.ip = ip
}
describe('host path memory', () => {
beforeEach(() => {
storage.clear()
joinNetwork('WIFI', '192.168.1.23')
})
it('keeps the direct head start after a direct connection on the same network', async () => {
await recordHostGoodPath('host-1', 'direct')
joinNetwork('WIFI', '192.168.1.87')
expect(await lastGoodPathWasDirectHere('host-1')).toBe(true)
})
it('drops the head start for a direct record from another network', async () => {
await recordHostGoodPath('host-1', 'direct')
joinNetwork('WIFI', '10.0.4.12')
expect(await lastGoodPathWasDirectHere('host-1')).toBe(false)
})
it('drops the head start when the last good path was the relay', async () => {
await recordHostGoodPath('host-1', 'relay')
expect(await lastGoodPathWasDirectHere('host-1')).toBe(false)
})
it('drops the head start for a host with no record', async () => {
await recordHostGoodPath('host-2', 'direct')
expect(await lastGoodPathWasDirectHere('host-1')).toBe(false)
})
it('keeps a direct record made while a VPN hides the network type', async () => {
joinNetwork('UNKNOWN', '192.168.1.23')
await recordHostGoodPath('host-1', 'direct')
expect(await lastGoodPathWasDirectHere('host-1')).toBe(true)
})
it('keeps a cellular direct record across carrier address changes', async () => {
joinNetwork('CELLULAR', '100.64.12.9')
await recordHostGoodPath('host-1', 'direct')
joinNetwork('CELLULAR', '100.71.3.200')
expect(await lastGoodPathWasDirectHere('host-1')).toBe(true)
})
})
@@ -79,49 +79,4 @@ describe('host removal lifecycle', () => {
removeHostMock.mock.invocationCallOrder[0]
)
})
it("forgets the host's recorded update failures once it is gone", async () => {
removeHostMock.mockResolvedValue(undefined)
await removeHostAndCloseClient('host-1', vi.fn())
expect(forgetUpdateFailuresMock).toHaveBeenCalledWith('host-1')
})
it('keeps them while the host is still paired', async () => {
removeHostMock.mockRejectedValue(new Error('storage unavailable'))
await expect(removeHostAndCloseClient('host-1', vi.fn())).rejects.toThrow()
expect(forgetUpdateFailuresMock).not.toHaveBeenCalled()
})
it('still closes the client when forgetting them fails', async () => {
removeHostMock.mockResolvedValue(undefined)
forgetUpdateFailuresMock.mockRejectedValueOnce(new Error('disk'))
const closeHostClient = vi.fn()
await removeHostAndCloseClient('host-1', closeHostClient)
expect(closeHostClient).toHaveBeenCalledWith('host-1')
})
it("deletes the host's page cache and device store once it is gone, and keeps them while it is still paired", async () => {
removeHostMock.mockRejectedValueOnce(new Error('storage unavailable'))
await expect(removeHostAndCloseClient('host-1', vi.fn())).rejects.toThrow()
expect(deletePageCacheMock).not.toHaveBeenCalled()
expect(wipeHostStoreMock).not.toHaveBeenCalled()
removeHostMock.mockResolvedValue(undefined)
await removeHostAndCloseClient('host-1', vi.fn())
expect(deletePageCacheMock).toHaveBeenCalledWith('host-1')
expect(wipeHostStoreMock).toHaveBeenCalledWith('host-1')
expect(removeHostMock.mock.invocationCallOrder.at(-1)).toBeLessThan(
deletePageCacheMock.mock.invocationCallOrder[0]
)
expect(removeHostMock.mock.invocationCallOrder.at(-1)).toBeLessThan(
wipeHostStoreMock.mock.invocationCallOrder[0]
)
})
it('still removes the host when its page cache cannot be deleted', async () => {
removeHostMock.mockResolvedValue(undefined)
deletePageCacheMock.mockRejectedValueOnce(new Error('disk'))
const closeHostClient = vi.fn()
await expect(removeHostAndCloseClient('host-1', closeHostClient)).resolves.toBeUndefined()
expect(closeHostClient).toHaveBeenCalledWith('host-1')
})
})
@@ -3,8 +3,6 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { RpcClient } from './rpc-client'
import { useHostStatusGates, type HostStatusGates } from './host-status-gates'
import { startRuntimeStatusProbe } from './runtime-status-probe'
import { createFakeRpcClient } from '../mobile-web-shell/bridge-host-test-fakes'
const recordHostAppVersionMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined))
@@ -89,112 +87,6 @@ describe('useHostStatusGates', () => {
}
})
it('loads gates from the connected host', async () => {
const sendRequest = vi.fn().mockResolvedValue({
ok: true,
result: {
appVersion: '1.4.191',
capabilities: ['browser.screencast.v1'],
floatingWorkspaceEnabled: true,
machineName: 'studio',
hostPlatform: 'darwin'
}
})
const client = { sendRequest } as unknown as RpcClient
let gates: HostStatusGates | undefined
let renderer: ReactTestRenderer | undefined
function Probe({ hostId }: { hostId: string }): null {
gates = useHostStatusGates({ hostId, client, connState: 'connected' })
return null
}
try {
await act(async () => {
renderer = create(createElement(Probe, { hostId: 'host-1' }))
await Promise.resolve()
})
expect(gates).toMatchObject({
desktopAppVersion: '1.4.191',
hostCapabilities: ['browser.screencast.v1'],
floatingWorkspaceEnabled: true
})
expect(sendRequest).toHaveBeenCalledOnce()
expect(recordHostAppVersionMock).toHaveBeenCalledWith('host-1', '1.4.191')
expect(recordDescriptorFromStatusMock).toHaveBeenCalledWith(
'host-1',
expect.objectContaining({ machineName: 'studio', hostPlatform: 'darwin' })
)
} finally {
renderer?.unmount()
}
})
it('keeps the proven gates while the same client reconnects, pending until it re-answers', async () => {
let resolveReconnect: ((response: unknown) => void) | null = null
const pendingReconnect = new Promise((resolve) => {
resolveReconnect = resolve
})
const sendRequest = vi
.fn()
.mockResolvedValueOnce({
ok: true,
result: { capabilities: ['browser.screencast.v1'], floatingWorkspaceEnabled: true }
})
.mockReturnValueOnce(pendingReconnect)
const client = { sendRequest } as unknown as RpcClient
let gates: HostStatusGates | undefined
let renderer: ReactTestRenderer | undefined
function Probe({ connState }: { connState: 'connected' | 'disconnected' }): null {
gates = useHostStatusGates({ hostId: 'host-1', client, connState })
return null
}
try {
await act(async () => {
renderer = create(createElement(Probe, { connState: 'connected' }))
await Promise.resolve()
})
expect(gates?.floatingWorkspaceEnabled).toBe(true)
await act(async () => {
renderer?.update(createElement(Probe, { connState: 'disconnected' }))
})
// Retain proven capabilities through drops while awaiting re-verification.
expect(gates).toMatchObject({
hostCapabilities: ['browser.screencast.v1'],
floatingWorkspaceEnabled: true,
statusPending: false
})
await act(async () => {
renderer?.update(createElement(Probe, { connState: 'connected' }))
})
expect(gates).toMatchObject({
hostCapabilities: ['browser.screencast.v1'],
floatingWorkspaceEnabled: true,
statusPending: true
})
await act(async () => {
resolveReconnect?.({
ok: true,
result: { capabilities: ['terminal.quick-commands.v1'], floatingWorkspaceEnabled: true }
})
await pendingReconnect
})
expect(gates).toMatchObject({
hostCapabilities: ['terminal.quick-commands.v1'],
floatingWorkspaceEnabled: true,
statusPending: false
})
} finally {
renderer?.unmount()
}
})
it('fails closed when the same host reconnects on a replaced client', async () => {
const firstClient = {
sendRequest: vi.fn().mockResolvedValue({
@@ -229,96 +121,6 @@ describe('useHostStatusGates', () => {
}
})
it('re-reads a status that failed while the connection stayed up', async () => {
vi.useFakeTimers()
const sendRequest = vi
.fn()
.mockRejectedValueOnce(new Error('request timed out'))
.mockResolvedValueOnce({
ok: true,
result: {
capabilities: ['browser.screencast.v1'],
floatingWorkspaceEnabled: true,
machineName: 'studio'
}
})
const client = { sendRequest } as unknown as RpcClient
let gates: HostStatusGates | undefined
let renderer: ReactTestRenderer | undefined
function Probe(): null {
gates = useHostStatusGates({ hostId: 'host-1', client, connState: 'connected' })
return null
}
try {
await act(async () => {
renderer = create(createElement(Probe))
await Promise.resolve()
})
// Settled closed rather than pending, so a failed read never traps the host screen.
expect(gates).toMatchObject({
hostCapabilities: [],
statusPending: false,
statusReadable: false
})
expect(recordDescriptorFromStatusMock).not.toHaveBeenCalled()
await act(async () => {
await vi.advanceTimersByTimeAsync(1_000)
})
expect(sendRequest).toHaveBeenCalledTimes(2)
expect(gates).toMatchObject({
hostCapabilities: ['browser.screencast.v1'],
statusPending: false,
statusReadable: true
})
expect(recordDescriptorFromStatusMock).toHaveBeenCalledWith(
'host-1',
expect.objectContaining({ machineName: 'studio' })
)
} finally {
renderer?.unmount()
vi.useRealTimers()
}
})
it('settles closed on a refusal and re-reads until the host answers', async () => {
vi.useFakeTimers()
const sendRequest = vi
.fn()
.mockResolvedValueOnce({ ok: false, error: { code: 'unavailable', message: 'busy' } })
.mockResolvedValueOnce({ ok: true, result: { capabilities: ['browser.screencast.v1'] } })
const client = { sendRequest } as unknown as RpcClient
let gates: HostStatusGates | undefined
let renderer: ReactTestRenderer | undefined
function Probe(): null {
gates = useHostStatusGates({ hostId: 'host-1', client, connState: 'connected' })
return null
}
try {
await act(async () => {
renderer = create(createElement(Probe))
await Promise.resolve()
})
expect(gates).toMatchObject({ statusPending: false, statusReadable: false })
await act(async () => {
await vi.advanceTimersByTimeAsync(1_000)
})
expect(sendRequest).toHaveBeenCalledTimes(2)
expect(gates).toMatchObject({
hostCapabilities: ['browser.screencast.v1'],
statusReadable: true
})
} finally {
renderer?.unmount()
vi.useRealTimers()
}
})
it('settles closed and stops on a status this app cannot decode', async () => {
vi.useFakeTimers()
const sendRequest = vi.fn().mockResolvedValue({ ok: true, result: 'not a status' })
@@ -376,40 +178,4 @@ describe('useHostStatusGates', () => {
vi.useRealTimers()
}
})
it('is not pending on its first render when the connection probe already landed', async () => {
const client = createFakeRpcClient({ getGeneration: () => 1, getLastConnectedAt: () => 1_000 })
const stopConnectionProbe = startRuntimeStatusProbe(client, () => {})
client.requests[0]!.resolve({
ok: true,
id: '1',
result: { appVersion: '1.4.191', capabilities: ['browser.screencast.v1'] },
_meta: { runtimeId: 'r1' }
})
await Promise.resolve()
await Promise.resolve()
const renders: HostStatusGates[] = []
let renderer: ReactTestRenderer | undefined
function Probe(): null {
renders.push(useHostStatusGates({ hostId: 'host-1', client, connState: 'connected' }))
return null
}
try {
await act(async () => {
renderer = create(createElement(Probe))
await Promise.resolve()
})
expect(renders[0]).toMatchObject({
statusPending: false,
statusReadable: true,
desktopAppVersion: '1.4.191',
hostCapabilities: ['browser.screencast.v1']
})
} finally {
renderer?.unmount()
stopConnectionProbe()
}
})
})
@@ -1,91 +0,0 @@
import { describe, expect, it } from 'vitest'
import { MobileEndpointHysteresis } from './mobile-endpoint-hysteresis'
describe('mobile endpoint hysteresis', () => {
it('requires three authenticated direct successes across the observation and dwell windows', () => {
const policy = new MobileEndpointHysteresis(0)
expect(policy.recordDirectSuccess(60_000)).toBe(false)
expect(policy.recordDirectSuccess(75_000)).toBe(false)
expect(policy.recordDirectSuccess(90_000)).toBe(true)
const insufficientSamples = new MobileEndpointHysteresis(0)
expect(insufficientSamples.recordDirectSuccess(60_000)).toBe(false)
expect(insufficientSamples.recordDirectSuccess(90_000)).toBe(false)
expect(insufficientSamples.recordDirectSuccess(90_000)).toBe(true)
const shortObservation = new MobileEndpointHysteresis(0)
expect(shortObservation.recordDirectSuccess(60_000)).toBe(false)
expect(shortObservation.recordDirectSuccess(60_001)).toBe(false)
expect(shortObservation.recordDirectSuccess(60_002)).toBe(false)
expect(shortObservation.recordDirectSuccess(90_000)).toBe(true)
const shortDwell = new MobileEndpointHysteresis(0)
expect(shortDwell.recordDirectSuccess(0)).toBe(false)
expect(shortDwell.recordDirectSuccess(15_000)).toBe(false)
expect(shortDwell.recordDirectSuccess(30_000)).toBe(false)
expect(shortDwell.recordDirectSuccess(60_000)).toBe(true)
})
it('resets progress and observes cooldown after a failure', () => {
const policy = new MobileEndpointHysteresis(0)
policy.recordDirectSuccess(60_000)
policy.recordDirectFailure(61_000)
expect(policy.canProbe(120_999)).toBe(false)
expect(policy.canProbe(121_000)).toBe(true)
expect(policy.recordDirectSuccess(121_000)).toBe(false)
expect(policy.recordDirectSuccess(136_000)).toBe(false)
expect(policy.recordDirectSuccess(151_000)).toBe(true)
})
it('upgrades after two successes 3 s apart within the dwell once the phone joins a network', () => {
const policy = new MobileEndpointHysteresis(0)
policy.recordDirectFailure(10_000)
expect(policy.canProbe(20_000)).toBe(false)
policy.recordNetworkArrival()
expect(policy.canProbe(20_000)).toBe(true)
// The network change drops the relay socket, and its redial is a migration too.
policy.recordMigration(20_000)
expect(policy.recordDirectSuccess(20_000)).toBe(false)
expect(policy.recordDirectSuccess(22_999)).toBe(false)
expect(policy.recordDirectSuccess(23_000)).toBe(true)
})
it('needs three timer successes again after an arrival fails or upgrades', () => {
const failed = new MobileEndpointHysteresis(0)
failed.recordNetworkArrival()
failed.recordDirectFailure(0)
expect(failed.recordDirectSuccess(60_000)).toBe(false)
expect(failed.recordDirectSuccess(63_000)).toBe(false)
expect(failed.recordDirectSuccess(90_000)).toBe(true)
const upgraded = new MobileEndpointHysteresis(0)
upgraded.recordNetworkArrival()
upgraded.recordDirectSuccess(0)
expect(upgraded.recordDirectSuccess(3_000)).toBe(true)
upgraded.recordDirectMigration(3_000)
upgraded.recordMigration(70_000)
expect(upgraded.recordDirectSuccess(70_000)).toBe(false)
expect(upgraded.recordDirectSuccess(73_000)).toBe(false)
expect(upgraded.recordDirectSuccess(100_000)).toBe(false)
expect(upgraded.recordDirectSuccess(130_000)).toBe(true)
})
it('holds a second arrival upgrade until a dwell has passed since the first', () => {
const policy = new MobileEndpointHysteresis(0)
policy.recordNetworkArrival()
policy.recordDirectSuccess(0)
expect(policy.recordDirectSuccess(3_000)).toBe(true)
policy.recordDirectMigration(3_000)
policy.recordMigration(10_000)
// Wi-Fi at the edge of range rejoins inside the dwell.
policy.recordNetworkArrival()
expect(policy.arrivalWaitMs(10_000)).toBe(53_000)
expect(policy.recordDirectSuccess(10_000)).toBe(false)
expect(policy.recordDirectSuccess(13_000)).toBe(false)
expect(policy.recordDirectSuccess(63_000)).toBe(true)
})
})
@@ -59,24 +59,4 @@ describe('mobile endpoint supervisor direct probe', () => {
expect(vi.getTimerCount()).toBe(0)
logical.close()
})
it('returns to the LAN 3 s after joining Wi-Fi, inside the dwell and past a pending timer probe', async () => {
const logical = createStableLogicalRpcClient(new FakeSession('connected'), 'relay')
const openDirect = vi.fn(() => new FakeSession('connected'))
let localNetwork: string | null = null
const deps = dependencies({ openDirect, readLocalNetwork: vi.fn(async () => localNetwork) })
const supervisor = new MobileEndpointSupervisor(logical, host.id, relay, deps)
await supervisor.start()
await vi.advanceTimersByTimeAsync(5_000)
localNetwork = 'WIFI:192.168.1'
supervisor.nudge('network-change')
await vi.advanceTimersByTimeAsync(0)
expect(openDirect).toHaveBeenCalledOnce()
expect(logical.getActivePath()).toBe('relay')
await vi.advanceTimersByTimeAsync(3_000)
expect(openDirect).toHaveBeenCalledTimes(2)
expect(logical.getActivePath()).toBe('lan')
supervisor.stop()
logical.close()
})
})
+1 -2
View File
@@ -6,9 +6,8 @@
"exclude": [
"node_modules",
// Outside this RN program: RN's numeric timers and Expo's process.env break the desktop graphs these
// tests import. The two roots of tsconfig.test.node.json are checked there against emitted
// tests import. The roots of tsconfig.test.node.json are checked there against emitted
// declarations; the others are legacy runtime-only coverage whose test bodies nothing typechecks.
"src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts",
"src/components/WorktreeAgentList.runtime-lineage.test.tsx",
"src/components/pr-sidebar/reviewer-picker.target-contract.test.tsx",
"src/session/mobile-native-command-discovery.test.tsx",
-1
View File
@@ -30,7 +30,6 @@
},
"files": [
"src/components/pr-sidebar/reviewer-picker.target-contract.test.tsx",
"src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts",
"../src/types/build-constants.d.ts"
],
"include": [],
@@ -1,30 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createHookListenerState } from './listener-state'
import { withClaudeToolRequestId } from './claude-tool-request-identity'
describe('Claude open-call tracking', () => {
it("reads a batch's calls once however many calls are open", () => {
const readsFor = (openCalls: number): number => {
const state = createHookListenerState()
for (let index = 0; index < openCalls; index++) {
withClaudeToolRequestId(state, 'pane', 'PreToolUse', {
tool_name: 'Read',
tool_input: { file_path: `/tmp/file-${index}` },
tool_use_id: `toolu-open-${index}`
})
}
let reads = 0
const toolCalls = Array.from({ length: 1000 }, (_, index) => ({
get tool_use_id() {
reads++
return `toolu-batch-${index}`
}
}))
withClaudeToolRequestId(state, 'pane', 'PostToolBatch', { tool_calls: toolCalls })
return reads
}
// Settling needs each listed call's ID once; the open calls are matched against that set.
expect(readsFor(1)).toBe(1000)
expect(readsFor(32)).toBe(readsFor(1))
})
})
@@ -1,49 +0,0 @@
import { describe, expect, it } from 'vitest'
import { resolveAgentStartupPlanInputs } from './agent-startup-plan-inputs'
import { buildAgentStartupPlan } from './tui-agent-startup'
import { tokenizeStartupCommand } from './tui-agent-startup-shell'
function agy(extraAgentArgs: string, defaults: string): string[] {
const plan = buildAgentStartupPlan({
...resolveAgentStartupPlanInputs({
agent: 'antigravity',
settings: { agentDefaultArgs: { antigravity: defaults } },
extraAgentArgs,
platform: 'linux',
isRemote: false,
shell: 'posix'
}),
prompt: 'go'
})
const parsed = tokenizeStartupCommand(plan?.launchCommand ?? '', 'posix')
if (!parsed.ok) {
throw new Error(parsed.error)
}
return parsed.tokens
}
describe('Antigravity automation extras', () => {
it('replace the default model and effort and keep other defaults', () => {
expect(
agy(
'--model gemini-4-argon --effort=high',
'--dangerously-skip-permissions --model=old --effort low'
)
).toEqual([
'agy',
'--dangerously-skip-permissions',
'--model',
'gemini-4-argon',
'--effort=high',
'--prompt-interactive',
'go'
])
})
it('refuse permission and mode flags', () => {
expect(() => agy('--dangerously-skip-permissions', '')).toThrow(
'"--dangerously-skip-permissions" isn\'t allowed'
)
expect(() => agy('--mode auto', '')).toThrow('"--mode" isn\'t allowed')
})
})
@@ -1,60 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
resolveAgentStartupPlanInputs,
type AgentStartupSettings
} from './agent-startup-plan-inputs'
import { buildAgentStartupPlan } from './tui-agent-startup'
import { tokenizeStartupCommand } from './tui-agent-startup-shell'
function pi(extraAgentArgs: string, settings: AgentStartupSettings): string[] {
const plan = buildAgentStartupPlan({
...resolveAgentStartupPlanInputs({
agent: 'pi',
settings,
extraAgentArgs,
platform: 'linux',
isRemote: false,
shell: 'posix'
}),
prompt: '',
allowEmptyPromptLaunch: true
})
const parsed = tokenizeStartupCommand(plan?.launchCommand ?? '', 'posix')
if (!parsed.ok) {
throw new Error(parsed.error)
}
return parsed.tokens
}
describe('Pi automation extras', () => {
it('replace the model and thinking within the pinned provider, keeping its key', () => {
const defaults = { pi: '--provider openrouter --api-key key --model old --thinking low' }
expect(pi('--model=anthropic/claude --thinking high', { agentDefaultArgs: defaults })).toEqual([
'pi',
'--provider',
'openrouter',
'--api-key',
'key',
'--model',
'anthropic/claude',
'--thinking',
'high'
])
expect(() => pi('--thinking extreme', { agentDefaultArgs: defaults })).toThrow(
/--thinking accepts off/
)
})
it('keep dash-leading operands of default options', () => {
expect(
pi('--model new', { agentDefaultArgs: { pi: '--system-prompt --model --model old' } })
).toEqual(['pi', '--system-prompt', '--model', '--model', 'new'])
// Pi reads `--api-key` here as the model's value, so it goes with the removed default.
expect(pi('--model new', { agentDefaultArgs: { pi: '--model --api-key key' } })).toEqual([
'pi',
'key',
'--model',
'new'
])
})
})
@@ -1,28 +0,0 @@
import { describe, expect, it } from 'vitest'
import { titleShowsNoAgent } from './shell-process-detection'
describe('titleShowsNoAgent', () => {
it.each([
'MINGW64:/c/Users/dev/repo',
'MINGW32:/c/repo',
'MSYS:/home/dev',
'UCRT64:/c/repo',
'CLANG64:/c/repo',
'CLANGARM64:/c/repo'
])('reads the Git Bash prompt title %s as the shell', (title) => {
expect(titleShowsNoAgent(title)).toBe(true)
})
it('still reads shell names and the default title as the shell', () => {
expect(titleShowsNoAgent('zsh')).toBe(true)
expect(titleShowsNoAgent('bash.exe')).toBe(true)
expect(titleShowsNoAgent('Terminal 2', 'Terminal 2')).toBe(true)
})
it.each(['demo-repo', 'Codex', '⠋ MINGW64:/c/repo', 'MINGW64 notes', 'mingw64:/c/repo', ''])(
'does not read %j as the shell',
(title) => {
expect(titleShowsNoAgent(title)).toBe(false)
}
)
})
@@ -1,33 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
import { createSessionSearchClient, unavailableSessionSearchStatus } from './ai-vault-search-client'
import { AiVaultSearchRequestSchema as LegacyRequestSchema } from '../../__fixtures__/pre-qoder-search-request'
import { searchHit, searchResults } from './ai-vault-search-test-fixture'
import { AI_VAULT_AGENTS } from '../contracts/ai-vault-types'
import { searchResults } from './ai-vault-search-test-fixture'
describe.each(['qoder', 'jcode'] as const)('%s search negotiation', (agent) => {
const supportField = agent === 'qoder' ? 'supportsQoderHistory' : 'supportsJcodeHistory'
it.each(['runtime', 'relay'] as const)(
'sends no search request for an unsupported agent over %s',
async (transport) => {
const search = vi.fn((params: unknown) => {
LegacyRequestSchema.parse(params)
return searchResults()
})
const status = vi.fn(() => unavailableSessionSearchStatus())
const client = createSessionSearchClient(
async (method, params) => (method === 'aiVault.searchStatus' ? status() : search(params)),
transport
)
expect(await client.searchSessions({ query: 'q', filters: { agents: [agent] } })).toEqual({
kind: 'unavailable',
reason: 'unsupported-agent'
})
expect(status).toHaveBeenCalledTimes(1)
expect(search).not.toHaveBeenCalled()
}
)
it.each(['runtime', 'relay'] as const)(
'retains the supported filters through the actual old enum over %s',
async (transport) => {
@@ -63,79 +39,9 @@ describe.each(['qoder', 'jcode'] as const)('%s search negotiation', (agent) => {
expect(search).toHaveBeenCalledTimes(1)
}
)
it.each(['runtime', 'relay'] as const)(
'preserves the requested agent identity only after positive host attestation over %s',
async (transport) => {
const call = vi.fn(async (method: string) =>
method === 'aiVault.searchStatus'
? { ...unavailableSessionSearchStatus(), [supportField]: true }
: { ...searchResults(), hits: [{ ...searchHit(), agent }] }
)
const result = await createSessionSearchClient(call, transport).searchSessions({
query: 'q',
filters: { agents: [agent] }
})
expect(call.mock.calls.map(([method]) => method)).toEqual([
'aiVault.searchStatus',
'aiVault.searchSessions'
])
expect(call).toHaveBeenLastCalledWith('aiVault.searchSessions', {
query: 'q',
limit: 20,
filters: { agents: [agent] },
supportedAgents: [...AI_VAULT_AGENTS],
supportsQoderHistory: true,
supportsJcodeHistory: true
})
expect(result).toMatchObject({ kind: 'results', hits: [{ agent }] })
}
)
it('does not dispatch a search when the capability probe loses host contact', async () => {
const call = vi.fn(async () => {
throw new Error('host disconnected')
})
await expect(
createSessionSearchClient(call, 'relay').searchSessions({
query: 'q',
filters: { agents: [agent, 'codex'] }
})
).rejects.toThrow('host disconnected')
expect(call).toHaveBeenCalledExactlyOnceWith('aiVault.searchStatus', {})
})
})
describe('explicit search host vocabulary', () => {
it.each(['runtime', 'relay'] as const)(
'retains current Jcode support even with no indexed sessions over %s',
async (transport) => {
const call = vi.fn(async (method: string) =>
method === 'aiVault.searchStatus'
? {
...unavailableSessionSearchStatus(),
supportedAgents: [...AI_VAULT_AGENTS, 'future-agent'],
sessionsByAgent: {}
}
: { ...searchResults(), hits: [{ ...searchHit(), agent: 'jcode' }] }
)
expect(
await createSessionSearchClient(call, transport).searchSessions({
query: 'q',
filters: { agents: ['jcode'] }
})
).toMatchObject({ hits: [{ agent: 'jcode' }] })
expect(call).toHaveBeenLastCalledWith('aiVault.searchSessions', {
query: 'q',
limit: 20,
filters: { agents: ['jcode'] },
supportedAgents: [...AI_VAULT_AGENTS],
supportsQoderHistory: true,
supportsJcodeHistory: true
})
}
)
it('uses an explicit host catalog before either historical capability', async () => {
const call = vi.fn(async (method: string) =>
method === 'aiVault.searchStatus'
@@ -1,17 +1,10 @@
import { describe, expect, it } from 'vitest'
import { AiVaultSearchResponseSchema, AiVaultSearchStatusSchema } from './ai-vault-search-contract'
import { searchHit, searchResults } from './ai-vault-search-test-fixture'
import { AiVaultSearchStatusSchema } from './ai-vault-search-contract'
import { searchHit } from './ai-vault-search-test-fixture'
import { redactForTransport, redactStatusForTransport } from './ai-vault-search-transport'
import { unavailableSessionSearchStatus } from './ai-vault-search-client'
describe('session search public contract', () => {
it('never accepts resume commands for an unverified or missing source', () => {
for (const presence of ['unverifiable', 'missing'] as const) {
const response = searchResults()
response.hits[0].source.presence = presence
expect(AiVaultSearchResponseSchema.safeParse(response).success).toBe(false)
}
})
it.each(['ipc', 'runtime', 'relay'] as const)(
'enforces the %s exposure policy without mutating the hit',
(transport) => {
@@ -51,19 +44,4 @@ describe('session search public contract', () => {
])
}
)
it.each([
'/host/private/path could not be listed.',
"EACCES: permission denied, scandir '/host/private/path'",
"EACCES: permission denied, scandir 'C:\\Users\\private\\sessions'"
])('withholds paths embedded in relay diagnostics: %s', (reason) => {
const status = {
...unavailableSessionSearchStatus(),
degradedRoots: [{ root: '/host/private/path', reason }]
}
const result = redactStatusForTransport(status, 'relay')
expect(result.degradedRoots).toHaveLength(1)
expect(JSON.stringify(result)).not.toContain('/host/private/path')
expect(JSON.stringify(result)).not.toContain('private')
expect(redactStatusForTransport(status, 'runtime')).toEqual(status)
})
})
@@ -1,21 +0,0 @@
import { describe, expect, it } from 'vitest'
import { AiVaultSearchRequestSchema } from './ai-vault-search-contract'
import './ai-vault-search-test-fixture'
describe('scope identity on the search request', () => {
it('refuses an identity sent alongside explicit scope paths', () => {
expect(() =>
AiVaultSearchRequestSchema.parse({
query: 'needle',
within: { kind: 'project', projectKey: 'repo:repo-1' },
filters: { scopePaths: ['/work/app'] }
})
).toThrow(/either a scope identity or explicit scope paths/)
})
it('refuses an unknown identity kind rather than dropping the narrowing', () => {
expect(() =>
AiVaultSearchRequestSchema.parse({ query: 'needle', within: { kind: 'repo', repoId: 'r' } })
).toThrow()
})
})
@@ -12,32 +12,6 @@ const query = {
}
describe.each(['runtime', 'relay'] as const)('missing search status over %s', (transport) => {
it.each([-32601, 'method_not_found'])(
'searches legacy filters after status refusal %s',
async (code) => {
const call = vi.fn(async (method: string, params: Record<string, unknown>) => {
if (method === 'aiVault.searchStatus') {
throw { code }
}
expect(LegacyRequestSchema.parse(params)).toEqual({
...query,
filters: { ...query.filters, agents: ['claude'] }
})
return searchResults()
})
expect(
await createSessionSearchClient(call, transport).searchSessions({
...query,
filters: { ...query.filters, agents: ['claude'] }
})
).toMatchObject({ kind: 'results' })
expect(call.mock.calls.map(([method]) => method)).toEqual([
'aiVault.searchStatus',
'aiVault.searchSessions'
])
}
)
it('keeps only the conservative legacy subset when status is absent', async () => {
const call = vi.fn(async (method: string, params: Record<string, unknown>) => {
if (method === 'aiVault.searchStatus') {
@@ -88,17 +62,6 @@ describe.each(['runtime', 'relay'] as const)('missing search status over %s', (t
expect(call).toHaveBeenCalledExactlyOnceWith('aiVault.searchStatus', {})
})
it('propagates a malformed status instead of assuming a legacy host', async () => {
const call = vi.fn(async () => ({ supportedAgents: ['claude'] }))
await expect(
createSessionSearchClient(call, transport).searchSessions({
query: 'needle',
filters: { agents: ['claude'] }
})
).rejects.toThrow()
expect(call).toHaveBeenCalledExactlyOnceWith('aiVault.searchStatus', {})
})
it('reports no service only when the search method itself is missing', async () => {
const call = vi.fn(async () => {
throw { code: 'method_not_found' }