test: remove 161 low-value cases and 12 suites

This commit is contained in:
OrcaWin
2026-11-11 04:39:50 -08:00
parent fd07f97d64
commit eb69a6ef1e
33 changed files with 50 additions and 5166 deletions
-134
View File
@@ -134,62 +134,6 @@ function nextMessage(socket: WebSocket): Promise<Record<string, unknown>> {
})
}
function nextRawMessage(socket: WebSocket): Promise<{ data: Buffer; binary: boolean }> {
return new Promise((resolveMessage, reject) => {
socket.once('message', (data, binary) =>
resolveMessage({ data: Buffer.from(data as ArrayBuffer), binary })
)
socket.once('error', reject)
})
}
async function attachPhone(input: {
host: WebSocket
hostAck: Record<string, unknown>
hostId: string
credential: string
}): Promise<{
phone: WebSocket
data: WebSocket
connId: string
hello: Record<string, unknown>
}> {
const headers = forwardedHeaders()
const phone = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/connect/${input.hostId}`, {
headers
})
await new Promise<void>((resolveOpen, reject) => {
phone.once('open', resolveOpen)
phone.once('error', reject)
})
const connOpenPromise = nextMessage(input.host)
phone.send(
JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: input.credential })
)
const connOpen = await connOpenPromise
expect(connOpen.type).toBe('conn-open')
const connId = String(connOpen.connId)
const data = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/host/data/${connId}`, {
headers
})
await new Promise<void>((resolveOpen, reject) => {
data.once('open', resolveOpen)
data.once('error', reject)
})
const helloPromise = nextMessage(phone)
data.send(
JSON.stringify({
type: 'host-data-auth',
v: 1,
connTicket: connOpen.connTicket,
generation: input.hostAck.generation
})
)
const hello = await helloPromise
expect(hello).toMatchObject({ type: 'relay-hello', ok: true })
return { phone, data, connId, hello }
}
async function openHostControl(input?: {
controlResumeSecret?: string
previousGeneration?: number
@@ -398,84 +342,6 @@ describe('served relay URL', () => {
host.socket.close()
})
it('attaches before success, preserves text/binary opcodes, installs, and confirms resume', async () => {
const host = await openHostControl()
const hostId = createHash('sha256')
.update(host.keyPair.publicKey)
.digest('base64url')
.slice(0, 16)
const invitePromise = nextMessage(host.socket)
host.socket.send(
JSON.stringify({ type: 'invite-create', reqId: 'invite-1', relayDeviceId: 'device-1' })
)
const invite = await invitePromise
expect(invite.type).toBe('invite-created')
const first = await attachPhone({
host: host.socket,
hostAck: host.ack,
hostId,
credential: String(invite.inviteToken)
})
const hostText = nextRawMessage(first.data)
first.phone.send('phone-text')
expect(await hostText).toEqual({ data: Buffer.from('phone-text'), binary: false })
const phoneBinary = nextRawMessage(first.phone)
first.data.send(Buffer.from([1, 2, 3]), { binary: true })
expect(await phoneBinary).toEqual({ data: Buffer.from([1, 2, 3]), binary: true })
const resumeToken = Buffer.alloc(32, 9).toString('base64url')
const installedPromise = nextMessage(host.socket)
host.socket.send(
JSON.stringify({
type: 'device-credential-install',
v: 1,
reqId: 'install-1',
relayDeviceId: 'device-1',
newResumeTokenHash: createHash('sha256').update(resumeToken).digest('base64url'),
authorization: { mode: 'relay-basis', basisConnId: first.connId }
})
)
const installed = await installedPromise
expect(installed).toMatchObject({
type: 'device-credential-installed',
authorizationMode: 'relay-basis',
currentVersion: 1
})
const resolved = await fetch(`${relayUrl}/v1/resolve`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ v: 1, relayHostId: hostId, resumeToken })
})
expect(resolved.status).toBe(200)
expect(await resolved.json()).toMatchObject({ v: 1, cellUrl: relayUrl, assignmentEpoch: 1 })
first.phone.close()
const resumed = await attachPhone({
host: host.socket,
hostAck: host.ack,
hostId,
credential: resumeToken
})
const confirmedPromise = nextMessage(host.socket)
host.socket.send(
JSON.stringify({
type: 'device-resume-confirm',
v: 1,
reqId: 'confirm-1',
basisConnId: resumed.connId
})
)
expect(await confirmedPromise).toMatchObject({
type: 'device-resume-confirmed',
renewed: true,
acceptedAs: 'current'
})
resumed.phone.close()
resumed.data.close()
host.socket.close()
})
it('uses configured-director recovery and typed 4503 on unplanned SIGTERM', async () => {
const originalUrl = relayUrl
const signalPort = await unusedPort()
-2
View File
@@ -446,7 +446,6 @@
4 test-no-wall-clock:src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts
5 test-no-wall-clock:src/main/agent-hooks/server/testing/replay/spool.test.ts
2 test-no-wall-clock:src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts
1 test-no-wall-clock:src/main/ai-vault-search/indexing/session-search-indexer.test.ts
1 test-no-wall-clock:src/main/ai-vault/parse-cache/session-parse-cache-preview-upgrade.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/cursor/session-scanner-cursor-chat-meta.test.ts
@@ -834,7 +833,6 @@
2 test-timeout-needs-reason:tests/e2e/paired-host-usage-credentials.spec.ts
7 test-timeout-needs-reason:tests/e2e/paired-instant-browser-tab.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-files-git-review.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-server-browser.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-workspace-visibility.spec.ts
2 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-tab-composition.spec.ts
File diff suppressed because one or more lines are too long
@@ -206,7 +206,6 @@
"config/scripts/ci/workflow-contracts/pr-workflow-parallelism.test.mjs": 161,
"config/scripts/desktop-distribution/runtime-verification/process-host-build-dist.test.mjs": 8298,
"config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts": 10910,
"config/scripts/orcad-distribution/server-bundle/profile-state-worker-smoke.test.mjs": 2740,
"config/scripts/development/web-client/project-renderer-web-client.test.mjs": 709,
"config/scripts/localization/catalog-validation/protected-copy-keys.test.mjs": 394,
"config/scripts/diagnostics/terminal-transcripts/pty-transcript-secret-scan.test.mjs": 188,
@@ -617,9 +616,7 @@
"src/main/agent-launch/trust/agent-trust-presets.test.ts": 377,
"src/main/agent-launch/trust/agent-workspace-trust.test.ts": 177,
"src/main/ai-vault-search/session-search-agent-compatibility.test.ts": 192,
"src/main/ai-vault-search/discovery/session-search-deleted-sources.test.ts": 675,
"src/main/ai-vault-search/indexing/session-search-dependent-transcripts.test.ts": 489,
"src/main/ai-vault-search/discovery/session-search-directory-listings.test.ts": 50,
"src/main/ai-vault-search/query/session-search-engine.test.ts": 2083,
"src/main/ai-vault-search/storage/session-search-file-write.test.ts": 696,
"src/main/ai-vault-search/query/session-search-hit-ranking.test.ts": 58,
@@ -642,7 +639,6 @@
"src/main/ai-vault-search/indexing/session-search-root-refresh.test.ts": 573,
"src/main/ai-vault-search/query/session-search-row-filter.test.ts": 274,
"src/main/ai-vault-search/storage/session-search-row-identity.test.ts": 134,
"src/main/ai-vault-search/discovery/session-search-scan-roots.test.ts": 235,
"src/main/ai-vault-search/storage/session-search-schema.test.ts": 876,
"src/main/ai-vault-search/scope/session-search-scope-resolution.test.ts": 117,
"src/main/ai-vault-search/session-search-service-registry.test.ts": 193,
@@ -4498,7 +4494,6 @@
"src/renderer/src/app-shell/use-profile-state-save-delay-notice.sonner.test.tsx": 355,
"src/renderer/src/app-shell/use-profile-state-save-delay-notice.test.tsx": 293,
"src/renderer/src/app-shell/visible-review-reporting.test.ts": 1872,
"src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx": 1170,
"src/renderer/src/app-shell/worktree-creation-chat-handoff.test.tsx": 2824,
"src/renderer/src/assets/theme-token-contrast.test.ts": 66,
"src/renderer/src/attention/agent-attention-policy.test.ts": 49,
@@ -4660,7 +4655,6 @@
"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.frame-lifecycle.test.tsx": 2678,
"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.settings-geometry.test.tsx": 2194,
"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.settings-lifetime.test.tsx": 2488,
"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx": 3334,
"src/renderer/src/components/dashboard-popout/dashboard-agent-status-patch.test.ts": 74,
"src/renderer/src/components/dashboard-popout/dashboard-preview-link-composition.test.tsx": 8657,
"src/renderer/src/components/dashboard-popout/preview-terminal-box-fit-lifecycle.test.ts": 192,
@@ -5888,7 +5882,6 @@
"src/renderer/src/hooks/useIpcEvents-agent-status-queue-ordering.test.ts": 3680,
"src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts": 4119,
"src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts": 3310,
"src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts": 5812,
"src/renderer/src/hooks/useIpcEvents-new-workspace-shortcut.test.ts": 72,
"src/renderer/src/hooks/useIpcEvents-runtime-environment-selectors.test.ts": 530,
"src/renderer/src/hooks/useIpcEvents-session-tab-close-request.test.ts": 2252,
@@ -7365,7 +7358,6 @@
"tests/e2e/SmartWorkspaceSourceResultList.linear-read-error.unit.test.ts": 3757,
"tests/e2e/agent-launch-cli.unit.test.ts": 2379,
"tests/e2e/agent-launch-setup-choice.unit.test.ts": 2657,
"tests/e2e/agent-model-catalog-renderer-cache.unit.test.ts": 2029,
"tests/e2e/ai-vault-manual-name-clear.unit.test.ts": 21206,
"tests/e2e/automation-chat-reopen.unit.test.ts": 6262,
"tests/e2e/codex-child-approval-activity-row.unit.test.ts": 14886,
@@ -1,10 +1,8 @@
import { mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { afterEach, expect, it } from 'vitest'
import { classifyNodeServerChanges, collectNodeServerInputs } from './node-server-change-scope.mjs'
import { runProcessSync } from '@orca/process-host'
import { NODE_SERVER_RUNNERS } from './node-server-qualification.mjs'
const temporaryDirs = []
afterEach(() => {
@@ -76,20 +74,6 @@ it('tracks workspace source and manifest closures without trusting dist or widen
).toBe(false)
})
it.each(['@orca/unknown', '@orca/process-host/private'])(
'retains qualification for an unresolved internal package export: %s',
async (specifier) => {
const root = workspaceTree(specifier)
const result = await classifyNodeServerChanges(
['src/packages/process-host/src/run-process.ts'],
() => collectNodeServerInputs({ root, entryPoints: ['entry.ts'] })
)
expect(result.shouldRun).toBe(true)
expect(result.graphUnavailable).toBe(true)
expect(result.reason).toContain('No public orca-source export')
}
)
it('checks ordinary source unit files against actual imports before skipping the matrix', async () => {
const reachable = 'src/main/persistence/example/used.test.ts'
const unrelated = 'src/main/persistence/example/unrelated.test.tsx'
@@ -118,92 +102,3 @@ it('retains qualification when a removed ordinary unit file breaks an actual imp
expect(result.reason).toContain('Dependency graph unavailable')
expect(result.reason).toContain('removed.test.ts')
})
it.each([
{ files: [], deferred: true, expected: 'should_run=true' },
{ files: ['package.json'], deferred: true, expected: 'should_run=true' },
{
files: ['src/main/persistence/profile-state/profile-state-windows.ts'],
deferred: true,
fullQualification: false,
qualification: false,
runners: ['ubuntu-22.04', 'windows-2022', 'windows-11-arm'],
expected: 'should_run=true'
},
{
files: ['src/main/persistence/profile-state/profile-state-windows.ts'],
deferred: true,
expected: 'should_run=true'
},
{
files: ['src/main/providers/provider-windows.ts'],
deferred: true,
fullQualification: false,
expected: 'should_run=true'
},
{
files: [
'src/main/persistence/profile-state/recovery/profile-state-recovery-crash-boundaries.test.ts'
],
deferred: true,
fullQualification: false,
pullRequest: true,
nativeGraph: true,
expected: 'should_run=true'
},
{ files: ['src/renderer/src/example.ts'], deferred: true, expected: 'graph_required=true' },
{ files: ['src/renderer/src/example.ts'], deferred: false, expected: 'should_run=true' }
])('fails closed or requests dependencies in an uninstalled checkout: %j', (scenario) => {
const root = moduleTree(
Object.fromEntries(
[
'node-server-change-scope',
'node-server-test-paths',
'node-server-qualification',
'node-server-native-compat-scope'
].map((name) => [
`config/scripts/node-server/qualification/${name}.mjs`,
readFileSync(new URL(`./${name}.mjs`, import.meta.url), 'utf8')
])
)
)
const changes = join(root, 'changes')
const stepOutput = join(root, 'step-output')
const statuses = join(root, 'native-diff')
writeFileSync(changes, scenario.files.map((file) => `${file}\0`).join(''))
writeFileSync(
statuses,
scenario.files
.map((file) => `:100644 100644 ${'1'.repeat(40)} ${'2'.repeat(40)} M\0${file}\0`)
.join('')
)
const result = runProcessSync({
program: process.execPath,
args: [
realpathSync(
join(root, 'config/scripts/node-server/qualification/node-server-change-scope.mjs')
),
changes,
...(scenario.fullQualification === false ? [] : ['--full-qualification']),
...(scenario.deferred ? ['--defer-graph'] : []),
...(scenario.pullRequest ? ['--pull-request', '--diff-paths', statuses] : [])
],
cwd: root,
env: { ...process.env, GITHUB_OUTPUT: stepOutput },
timeoutMs: 5_000
})
expect(result.code).toBe(0)
const output = readFileSync(stepOutput, 'utf8')
expect(output).toContain(scenario.expected)
if (scenario.nativeGraph) {
expect(output).toContain('graph_required=true')
expect(output).not.toContain('native_compatibility=')
}
if (scenario.expected === 'graph_required=true') {
expect(output).not.toContain('should_run=')
expect(output).not.toContain('runners=')
} else {
expect(output).toContain(`qualification=${scenario.qualification !== false}`)
expect(output).toContain(`runners=${JSON.stringify(scenario.runners ?? NODE_SERVER_RUNNERS)}`)
}
})
@@ -1,65 +0,0 @@
import { build } from 'esbuild'
import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { smokeProfileStateWorkers } from './profile-state-worker-smoke.mjs'
const directories = []
const writerFilename = 'profile-state-writer-worker-entry.js'
const backupFilename = 'profile-state-backup-worker-entry.js'
let builtDirectory
function fixtureDirectory() {
const directory = mkdtempSync(join(tmpdir(), 'orca-profile-worker-build-test-'))
directories.push(directory)
return directory
}
beforeAll(async () => {
builtDirectory = fixtureDirectory()
await Promise.all(
['writer', 'backup'].map((role) =>
build({
entryPoints: [
resolve(
`src/main/persistence/profile-state/${role}/profile-state-${role}-worker-entry.ts`
)
],
outfile: join(builtDirectory, `profile-state-${role}-worker-entry.js`),
bundle: true,
platform: 'node',
target: 'node18',
format: 'cjs',
logLevel: 'silent'
})
)
)
})
afterAll(() => {
for (const directory of directories) {
rmSync(directory, { recursive: true, force: true })
}
})
describe('profile state build smoke', () => {
it('writes through the built writer and verifies the built backup after handle release', async () => {
await expect(smokeProfileStateWorkers(builtDirectory)).resolves.toBeUndefined()
})
it('does not accept a successful backup response without the copied database', async () => {
const directory = fixtureDirectory()
copyFileSync(join(builtDirectory, writerFilename), join(directory, writerFilename))
writeFileSync(
join(directory, backupFilename),
`const { parentPort } = require('node:worker_threads')
parentPort.postMessage({ ok: true })
parentPort.close()`
)
await expect(smokeProfileStateWorkers(directory)).rejects.toMatchObject({
code: 'ERR_SQLITE_ERROR',
errcode: 14
})
})
})
@@ -97,20 +97,6 @@ afterEach(async () => {
})
describe('skill bundle manifest generator', () => {
it('orders complete manifest paths when a reference file shares a directory stem', async () => {
const packageRoot = await createPackage()
await mkdir(path.join(packageRoot, 'references', 'refs'), { recursive: true })
await writeFile(path.join(packageRoot, 'SKILL.md'), 'skill\n')
await writeFile(path.join(packageRoot, 'references', 'refs.md'), 'reference\n')
await writeFile(path.join(packageRoot, 'references', 'refs', 'image.webp'), Buffer.from([0]))
expect((await collectPackageFiles(packageRoot)).map((file) => file.path)).toEqual([
'SKILL.md',
'references/refs.md',
'references/refs/image.webp'
])
})
it('keeps SKILL.md bytes only a release tag shipped, off HEAD', async () => {
const sandbox = await createGeneratorSandbox()
sandbox.git('init', '-q', '-b', 'main')
@@ -128,17 +114,6 @@ describe('skill bundle manifest generator', () => {
expect(digests).toHaveLength(2)
})
it('fails when a digest is missing or the pull request base cannot be read', async () => {
const sandbox = await createGeneratorSandbox()
sandbox.generate('--write')
expect(() => sandbox.generateOnPullRequest()).toThrow(/Cannot read the pull request base/)
await writeFile(
path.join(sandbox.root, 'resources', 'skills', 'released-digests.json'),
`${JSON.stringify({ schemaVersion: 1, skills: { demo: [] } }, null, 2)}\n`
)
expect(() => sandbox.generate()).toThrow(/stale/)
})
it.runIf(process.platform !== 'win32')(
'rejects executable files in shipped skill packages',
async () => {
@@ -162,7 +162,6 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts',
'src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx',
'src/main/claude/claude-agent-sdk-contract-pins.test.ts',
'config/scripts/orcad-distribution/server-bundle/profile-state-worker-smoke.test.mjs',
'config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts',
'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts',
// Reopen WAL-backed row caches read-only, which Bun on macOS cannot.
@@ -13,44 +13,6 @@ function deferred<T>() {
}
describe('PrActionsEngine — PR identity changes', () => {
it('clears reviewer optimism when switching PR identity', async () => {
const slow = deferred<GitHubPrMutationOutcome>()
const mutations: PrActionMutations = {
mergePR: async () => ({ ok: true }),
setPRAutoMerge: async () => ({ ok: true }),
updatePRState: async () => ({ ok: true }),
markReadyForReview: async () => ({ ok: true }),
markDraft: async () => ({ ok: true }),
requestReviewers: async () => slow.promise,
removeReviewers: async () => ({ ok: true }),
rerunChecks: async () => ({ ok: true })
}
const refetch = vi.fn()
const onChange = vi.fn()
const engine = new PrActionsEngine({
mutations,
prNumber: 1,
refetch,
onChange
})
const action = engine.requestReviewer('alice')
expect(engine.resolveReviewerRequested('alice', false)).toBe(true)
engine.updateConfig({
mutations,
prNumber: 2,
refetch,
onChange
})
expect(engine.resolveReviewerRequested('alice', false)).toBe(false)
slow.resolve({ ok: false, error: 'connection lost' })
await action
expect(engine.error).toBeNull()
expect(refetch).not.toHaveBeenCalled()
})
it('clears in-flight state when only the GitHub host changes', async () => {
const slow = deferred<GitHubPrMutationOutcome>()
const mutations: PrActionMutations = {
@@ -8,19 +8,16 @@ import {
} from '../../../src/shared/worktree/retired-name-registry'
import { useRetiredWorktreeNames } from './use-retired-worktree-names'
type Pending = { resolve: (response: unknown) => void; reject: (err: Error) => void }
type Pending = { resolve: (response: unknown) => void }
// Defer RPC replies to control both their repo and arrival order.
function mountNames() {
const pending: Pending[] = []
const requests: { method: string; params: unknown }[] = []
let latest: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The hook only calls this fixture's deferred sendRequest method.
const client = {
sendRequest: (method: string, params: unknown) => {
requests.push({ method, params })
return new Promise<unknown>((resolve, reject) => pending.push({ resolve, reject }))
}
sendRequest: () => new Promise<unknown>((resolve) => pending.push({ resolve }))
} as unknown as RpcClient
function Probe({ repoId, refreshKey }: { repoId: string | null; refreshKey: string }) {
@@ -33,13 +30,9 @@ function mountNames() {
renderer = create(createElement(Probe, { repoId: 'repo-1', refreshKey: 'a' }))
})
return {
get registry(): RetiredNameRegistry {
return latest
},
get names(): readonly string[] {
return latest.names
},
requests,
rerender(props: { repoId: string | null; refreshKey: string }) {
act(() => {
renderer.update(createElement(Probe, props))
@@ -58,29 +51,11 @@ function mountNames() {
})
await Promise.resolve()
})
},
async fail(index: number) {
await act(async () => {
pending[index]!.reject(new Error('host unreachable'))
await Promise.resolve()
})
}
}
}
describe('useRetiredWorktreeNames', () => {
// Match desktop: refresh failure must not un-retire every name for the rest of the sheet session.
it('keeps previously loaded names when a refresh fails', async () => {
const probe = mountNames()
await probe.settle(0, { 'repo-1': ['nautilus'] })
expect(probe.names).toEqual(['nautilus'])
probe.rerender({ repoId: 'repo-1', refreshKey: 'b' })
await probe.fail(1)
expect(probe.names).toEqual(['nautilus'])
})
it('drops names when the repo changes rather than showing another repo pool', async () => {
const probe = mountNames()
await probe.settle(0, { 'repo-1': ['nautilus'] })
+3 -235
View File
@@ -1,27 +1,20 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import * as fs from 'node:fs'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import type * as fs from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createDefaultLocalOrcaProfile,
DEFAULT_LOCAL_ORCA_PROFILE_ID
} from '../../shared/orca-profiles'
import { getDefaultPersistedState } from '../../shared/constants'
import type { PersistedState } from '../../shared/persisted-state-types'
import { createDefaultLocalOrcaProfile } from '../../shared/orca-profiles'
import {
getOrcaProfileDataFile,
getOrcaProfileStateDatabaseFile
} from '../../main/orca-profiles/profile-storage-paths'
import { openProfileStateDatabase } from '../../main/persistence/profile-state/database/profile-state-database'
import * as profileStateDatabase from '../../main/sqlite/sync-database'
import {
exportProfileStateJson,
importProfileStateJson
} from '../../main/persistence/profile-state/documents/profile-state-documents'
import { hashProfileStatePayload as hashProfileStateJson } from '../../main/persistence/profile-state/documents/profile-state-document-validation'
import {
acquireProfileStateMaintenance,
acquireProfileStateRuntimeAdmission,
type ProfileStateRuntimeAdmission
} from '../../main/persistence/profile-state/access/profile-state-access'
@@ -89,11 +82,6 @@ vi.mock('../../main/agent-hooks/installation/managed-agent-hook-controls', () =>
import { main } from '../index'
function writeDataFile(userDataPath: string, state: PersistedState): void {
mkdirSync(userDataPath, { recursive: true })
writeFileSync(join(userDataPath, 'orca-data.json'), JSON.stringify(state, null, 2), 'utf-8')
}
function writeActiveProfileIndex(userDataPath: string, profileId: string): void {
writeFileSync(
join(userDataPath, 'orca-profile-index.json'),
@@ -130,116 +118,6 @@ describe('agent hooks CLI handler', () => {
rmSync(userDataPath, { recursive: true, force: true })
})
it.each(['fresh', 'root-json', 'profile-json'] as const)(
'refuses an incapable offline writer before any %s profile or hook changes',
async (source) => {
const profileId = 'unsupported-runtime'
const state = getDefaultPersistedState(userDataPath)
const directory =
source === 'profile-json' ? join(userDataPath, 'profiles', profileId) : userDataPath
if (source !== 'fresh') {
writeDataFile(directory, state)
}
if (source === 'profile-json') {
writeActiveProfileIndex(userDataPath, profileId)
}
vi.spyOn(profileStateDatabase, 'isSqliteAvailable').mockReturnValue(false)
await runAgentHooksOff(userDataPath)
expect(process.exitCode).toBe(1)
expect(applyAgentStatusHooksEnabledMock).not.toHaveBeenCalled()
expect(existsSync(join(userDataPath, '.profile-state-access'))).toBe(false)
expect(existsSync(getOrcaProfileStateDatabaseFile(profileId, userDataPath))).toBe(false)
expect(
existsSync(getOrcaProfileStateDatabaseFile(DEFAULT_LOCAL_ORCA_PROFILE_ID, userDataPath))
).toBe(false)
if (source !== 'fresh') {
expect(JSON.parse(readFileSync(join(directory, 'orca-data.json'), 'utf8'))).toEqual(state)
}
if (source !== 'profile-json') {
expect(existsSync(join(userDataPath, 'orca-profile-index.json'))).toBe(false)
}
expect(console.log).toHaveBeenCalledWith(expect.stringContaining('bundled Orca CLI'))
}
)
it.each(['root', 'indexed'] as const)(
'reads %s JSON status without SQLite or migration',
async (source) => {
const profileId = 'read-only'
const directory =
source === 'indexed' ? join(userDataPath, 'profiles', profileId) : userDataPath
writeDataFile(directory, getDefaultPersistedState(userDataPath))
if (source === 'indexed') {
writeActiveProfileIndex(userDataPath, profileId)
}
getDefaultUserDataPathMock.mockReturnValue(userDataPath)
vi.spyOn(profileStateDatabase, 'isSqliteAvailable').mockReturnValue(false)
const original = readFileSync(join(directory, 'orca-data.json'), 'utf8')
await main(['agent', 'hooks', 'status', '--json'], userDataPath)
expect(process.exitCode).not.toBe(1)
expect(readFileSync(join(directory, 'orca-data.json'), 'utf8')).toBe(original)
expect(existsSync(join(directory, 'profile-state.db'))).toBe(false)
expect(applyAgentStatusHooksEnabledMock).not.toHaveBeenCalled()
}
)
it.each(['missing', 'corrupt'] as const)(
'uses the backup index when the primary is %s',
async (primary) => {
const profileId = 'backup-selected'
const indexPath = join(userDataPath, 'orca-profile-index.json')
writeActiveProfileIndex(userDataPath, profileId)
fs.renameSync(indexPath, `${indexPath}.bak`)
if (primary === 'corrupt') {
writeFileSync(indexPath, '{broken')
}
writeDataFile(
join(userDataPath, 'profiles', profileId),
getDefaultPersistedState(userDataPath)
)
await runAgentHooksOff(userDataPath)
expect(process.exitCode).not.toBe(1)
expect(existsSync(getOrcaProfileStateDatabaseFile(profileId, userDataPath))).toBe(true)
expect(
existsSync(getOrcaProfileStateDatabaseFile(DEFAULT_LOCAL_ORCA_PROFILE_ID, userDataPath))
).toBe(false)
const { ensureActiveOrcaProfile } =
await import('../../main/orca-profiles/profile-index-store.js')
expect(ensureActiveOrcaProfile(userDataPath).profile.id).toBe(profileId)
const opened = openProfileStateDatabase(
getOrcaProfileStateDatabaseFile(profileId, userDataPath),
profileId
)
try {
expect(JSON.parse(exportProfileStateJson(opened.db)).settings.agentStatusHooksEnabled).toBe(
false
)
} finally {
opened.db.close()
}
}
)
it.each([0])('refuses a pre-index root with only legacy backup %s', async (slot) => {
const backup = join(userDataPath, `orca-data.json.bak.${slot}`)
const source = '{"settings":{"agentStatusHooksEnabled":true}}'
writeFileSync(backup, source)
await runAgentHooksOff(userDataPath)
expect(process.exitCode).toBe(1)
expect(readFileSync(backup, 'utf8')).toBe(source)
expect(existsSync(join(userDataPath, 'orca-profile-index.json'))).toBe(false)
expect(existsSync(join(userDataPath, 'profiles'))).toBe(false)
expect(applyAgentStatusHooksEnabledMock).not.toHaveBeenCalled()
})
it.each(['root-json', 'profile-json', 'sqlite'] as const)(
'refuses offline %s mutation when startup wins after the stopped-status response',
async (backend) => {
@@ -296,57 +174,6 @@ describe('agent hooks CLI handler', () => {
}
)
it.each(['root-json', 'profile-json'] as const)(
'excludes startup and other offline writers through %s publication',
async (backend) => {
const profileId = 'offline-first'
const directory =
backend === 'root-json' ? userDataPath : join(userDataPath, 'profiles', profileId)
mkdirSync(directory, { recursive: true })
if (backend === 'profile-json') {
writeActiveProfileIndex(userDataPath, profileId)
}
const dataFile = join(directory, 'orca-data.json')
writeFileSync(dataFile, JSON.stringify({ settings: { agentStatusHooksEnabled: true } }))
const databaseFile = getOrcaProfileStateDatabaseFile(
backend === 'root-json' ? DEFAULT_LOCAL_ORCA_PROFILE_ID : profileId,
userDataPath
)
const link = fs.linkSync
let checkedPublication = false
vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
if (target === databaseFile) {
checkedPublication = true
expect(() => acquireProfileStateRuntimeAdmission(userDataPath)).toThrow()
expect(() => acquireProfileStateMaintenance(userDataPath)).toThrow()
}
return link(source, target)
})
await runAgentHooksOff(userDataPath)
expect(checkedPublication).toBe(true)
expect(process.exitCode).not.toBe(1)
const runtime = acquireProfileStateRuntimeAdmission(userDataPath)
try {
const opened = openProfileStateDatabase(
databaseFile,
backend === 'root-json' ? DEFAULT_LOCAL_ORCA_PROFILE_ID : profileId
)
try {
expect(
JSON.parse(exportProfileStateJson(opened.db)).settings.agentStatusHooksEnabled
).toBe(false)
} finally {
opened.db.close()
}
expect(JSON.parse(readFileSync(dataFile, 'utf8')).settings.agentStatusHooksEnabled).toBe(
true
)
} finally {
runtime.release()
}
}
)
it('updates an established SQLite profile without rewriting its JSON export', async () => {
const profileId = 'work-profile'
const profileDirectory = join(userDataPath, 'profiles', profileId)
@@ -389,63 +216,4 @@ describe('agent hooks CLI handler', () => {
readBack.db.close()
}
})
it('imports a JSON-only active profile before the first settings mutation', async () => {
const profileId = 'json-profile'
const profileDirectory = join(userDataPath, 'profiles', profileId)
mkdirSync(profileDirectory, { recursive: true })
writeDataFile(profileDirectory, getDefaultPersistedState(userDataPath))
writeActiveProfileIndex(userDataPath, profileId)
await runAgentHooksOff(userDataPath)
expect(existsSync(getOrcaProfileStateDatabaseFile(profileId, userDataPath))).toBe(true)
expect(
JSON.parse(readFileSync(getOrcaProfileDataFile(profileId, userDataPath), 'utf-8')).settings
.agentStatusHooksEnabled
).toBe(true)
const opened = openProfileStateDatabase(
getOrcaProfileStateDatabaseFile(profileId, userDataPath),
profileId
)
try {
expect(JSON.parse(exportProfileStateJson(opened.db)).settings.agentStatusHooksEnabled).toBe(
false
)
} finally {
opened.db.close()
}
})
it('fails closed when a profile has corrupt SQLite alongside legacy JSON', async () => {
const profileId = 'corrupt-profile'
const profileDirectory = join(userDataPath, 'profiles', profileId)
mkdirSync(profileDirectory, { recursive: true })
const state = getDefaultPersistedState(userDataPath)
writeDataFile(profileDirectory, state)
writeActiveProfileIndex(userDataPath, profileId)
const databaseFile = getOrcaProfileStateDatabaseFile(profileId, userDataPath)
writeFileSync(databaseFile, 'not sqlite', 'utf-8')
const before = readFileSync(getOrcaProfileDataFile(profileId, userDataPath), 'utf-8')
await runAgentHooksOff(userDataPath)
expect(process.exitCode).toBe(1)
expect(applyAgentStatusHooksEnabledMock).not.toHaveBeenCalled()
expect(readFileSync(getOrcaProfileDataFile(profileId, userDataPath), 'utf-8')).toBe(before)
expect(readFileSync(databaseFile, 'utf-8')).toBe('not sqlite')
})
it('fails closed when a profile index is present but unreadable', async () => {
const legacy = getDefaultPersistedState(userDataPath)
writeDataFile(userDataPath, legacy)
writeFileSync(join(userDataPath, 'orca-profile-index.json'), '{ torn', 'utf-8')
const before = readFileSync(join(userDataPath, 'orca-data.json'), 'utf-8')
await runAgentHooksOff(userDataPath)
expect(process.exitCode).toBe(1)
expect(applyAgentStatusHooksEnabledMock).not.toHaveBeenCalled()
expect(readFileSync(join(userDataPath, 'orca-data.json'), 'utf-8')).toBe(before)
})
})
@@ -1,58 +0,0 @@
import { describe, expect, it } from 'vitest'
import { WORKER_LIST_VIEW, WORKER_SHOW_VIEW } from './worker-agent-views'
describe('worker views of a worker a paired server runs', () => {
it('labels a remote worker’s show with its server, record time, last report and note', () => {
expect(
WORKER_SHOW_VIEW.fields({
dispatch: { id: 'ctx_w1', taskId: 'task_1', runId: 'run_1', status: 'dispatched' },
worker: {
dispatchId: 'ctx_w1',
state: 'ready',
stage: 'server_record',
agentTerminalHandle: null
},
projection: null,
observation: { reason: 'devB could not be reached, so this is this Orca’s record.' },
server: { name: 'devB', asOf: '2026-11-09T08:30:00Z', reachable: false },
lastReport: 'Halfway: tests written.'
})
).toMatchObject({
dispatchId: 'ctx_w1',
state: 'ready',
stage: 'server_record',
server: 'devB',
asOf: '2026-11-09T08:30:00Z',
lastReport: 'Halfway: tests written.',
note: 'devB could not be reached, so this is this Orca’s record.',
waitingOnHuman: 'unknown'
})
})
it('names a listed remote worker’s server, and says when its pairing was re-made', () => {
const row = {
taskId: 'task_1',
runId: 'run_1',
workerState: 'ready',
dispatchStatus: 'dispatched',
agentTerminalHandle: null,
terminalState: null
}
const fields = WORKER_LIST_VIEW.fields({
workers: [
{ ...row, dispatchId: 'ctx_w1', server: { name: 'devB', asOf: '2026-11-09T08:30:00Z' } },
{
...row,
dispatchId: 'ctx_w2',
server: { name: 'devB', asOf: '2026-11-09T08:45:00Z', repaired: true }
}
],
counts: {},
scope: { source: 'all' }
})
expect(fields.workers).toEqual([
expect.objectContaining({ dispatchId: 'ctx_w1', host: 'devB', asOf: '2026-11-09T08:30:00Z' }),
expect.objectContaining({ dispatchId: 'ctx_w2', host: 'devB (pairing re-made)' })
])
})
})
@@ -28,14 +28,12 @@ import {
profileStateDatabaseBackupPath
} from '../../main/persistence/profile-state/backup/profile-state-backup-path'
import { writeProfileStateDatabaseSnapshotAsync } from '../../main/persistence/profile-state/database/profile-state-database-snapshot'
import { restoreProfileStateDatabaseBackup } from '../../main/persistence/profile-state/recovery/profile-state-database-recovery'
import {
assertNoRetainedProfileStateExports,
ProfileStateRecoveryRequiredError
} from '../../main/persistence/profile-state/recovery/profile-state-recovery-required'
import { RuntimeClient } from '../runtime-client'
import { PROFILE_STATE_HANDLERS } from './profile-state'
import { rollbackProfileState } from '../../main/persistence/profile-state/recovery/profile-state-recovery-command'
import { profileStateJsonExportPath } from '../../main/persistence/profile-state/legacy-json/profile-state-export-path'
const mocks = vi.hoisted(() => ({ root: vi.fn(), status: vi.fn() }))
@@ -145,45 +143,6 @@ function state(databasePath: string) {
}
describe('offline recovery excludes runtime admission', () => {
it.each(['backup', 'latest-json'] as const)(
'refuses %s rollback without changing the database when a move journal is unresolved',
async (selector) => {
const profile = await fixture()
const before = readFileSync(profile.databasePath)
const intents = join(profile.root, 'profile-move-intents')
mkdirSync(intents)
const intentPath = join(intents, '00000000-0000-0000-0000-000000000001.json')
writeFileSync(intentPath, '{"partial":true}')
await expect(rollback(profile, selector)).rejects.toThrow('pending project move')
expect(readFileSync(profile.databasePath)).toEqual(before)
expect(readFileSync(intentPath, 'utf8')).toBe('{"partial":true}')
}
)
it.each(['backup', 'latest-json'] as const)(
'refuses %s recovery before any mutation when a runtime has already entered',
async (selector) => {
const profile = await fixture()
const original = readFileSync(profile.databasePath)
const backup = readFileSync(profile.backupPath)
const admission = acquireProfileStateRuntimeAdmission(profile.root)
const runtime = openProfileStateDatabase(profile.databasePath, profileId)
try {
await expect(rollback(profile, selector)).rejects.toThrow('in use')
expect(mocks.status).not.toHaveBeenCalled()
expect(JSON.parse(readProfileStateSnapshot(runtime.db).json)).toEqual(liveState)
expect(readFileSync(profile.databasePath)).toEqual(original)
expect(readFileSync(profile.backupPath)).toEqual(backup)
expect(
readdirSync(profile.directory).some((name) => name.startsWith('profile-state-corrupt'))
).toBe(false)
} finally {
runtime.db.close()
admission.release()
}
}
)
it('exports the latest SQLite revision through CLI before handing authority to an older build', async () => {
const profile = await fixture()
const staleJson = JSON.stringify(backupState)
@@ -290,56 +249,6 @@ describe('offline recovery excludes runtime admission', () => {
acquireProfileStateRuntimeAdmission(profile.root).release()
})
it('rejects fabricated or released maintenance before creating the latest export', async () => {
const profile = await fixture()
const maintenance = acquireProfileStateMaintenance(profile.root)
try {
expect(() =>
rollbackProfileState(profile.root, { kind: 'latest-json' }, { ...maintenance })
).toThrow('acquired')
} finally {
maintenance.release()
}
expect(() => rollbackProfileState(profile.root, { kind: 'latest-json' }, maintenance)).toThrow(
'released'
)
expect(existsSync(profileStateJsonExportPath(profile.dataFile, 2))).toBe(false)
expect(JSON.parse(state(profile.databasePath).json)).toEqual(liveState)
})
it.each(['missing', 'corrupt', 'newer-schema'] as const)(
'refuses a latest JSON handoff from a %s database instead of selecting stale JSON',
async (condition) => {
const profile = await fixture()
const staleJson = JSON.stringify(backupState)
writeFileSync(profile.dataFile, staleJson)
if (condition === 'missing') {
rmSync(profile.databasePath)
} else if (condition === 'corrupt') {
writeFileSync(profile.databasePath, 'corrupt SQLite')
} else {
const opened = openProfileStateDatabase(profile.databasePath, profileId)
opened.db.pragma('user_version = 999')
opened.db.close()
}
const before = existsSync(profile.databasePath)
? readFileSync(profile.databasePath)
: undefined
await expect(rollback(profile, 'latest-json')).rejects.toThrow()
expect(readFileSync(profile.dataFile, 'utf8')).toBe(staleJson)
expect(
existsSync(profile.databasePath) ? readFileSync(profile.databasePath) : undefined
).toEqual(before)
expect(existsSync(profile.backupPath)).toBe(true)
expect(existsSync(profileStateJsonExportPath(profile.dataFile, 2))).toBe(false)
expect(
readdirSync(profile.directory).some((name) => name.startsWith('profile-state-corrupt'))
).toBe(false)
}
)
it('blocks startup between the stopped census and restoration while preserving complete original and restored state', async () => {
const profile = await fixture()
const original = readFileSync(profile.databasePath)
@@ -413,17 +322,4 @@ describe('offline recovery excludes runtime admission', () => {
expect(JSON.parse(state(profile.databasePath).json)).toEqual(backupState)
acquireProfileStateRuntimeAdmission(profile.root).release()
})
it('rejects fabricated or released maintenance handles before replacing any database bytes', async () => {
const profile = await fixture()
const maintenance = acquireProfileStateMaintenance(profile.root)
const original = readFileSync(profile.databasePath)
const options = { ...profile, profileId }
expect(() =>
restoreProfileStateDatabaseBackup({ ...options, maintenance: { ...maintenance } })
).toThrow('acquired')
maintenance.release()
expect(() => restoreProfileStateDatabaseBackup({ ...options, maintenance })).toThrow('released')
expect(readFileSync(profile.databasePath)).toEqual(original)
})
})
+1 -451
View File
@@ -1,11 +1,9 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as ProcessHostModule from '@orca/process-host'
import * as durableFileWrite from '../../main/filesystem/durable-file-write'
import * as http1Marker from '../../main/startup/http1-compatibility-marker'
import { readPersistedHttp1CompatibilityMode } from '../../main/startup/http1-compatibility-profile-state'
import {
openProfileStateDatabase,
openProfileStateDatabaseReadOnly
@@ -15,13 +13,7 @@ import {
exportProfileStateJson,
importProfileStateJson
} from '../../main/persistence/profile-state/documents/profile-state-documents'
import {
createProfileStateDatabaseBackupId,
profileStateDatabaseBackupPath
} from '../../main/persistence/profile-state/backup/profile-state-backup-path'
import { writeProfileStateDatabaseSnapshotAsync } from '../../main/persistence/profile-state/database/profile-state-database-snapshot'
import { profileStateJsonExportPath } from '../../main/persistence/profile-state/legacy-json/profile-state-export-path'
import { PROFILE_STATE_RECOVERY_RESULT_PREFIX } from '../../shared/profile-state-recovery-command'
import { main } from '../index'
const {
@@ -124,32 +116,6 @@ function createProfile(): {
return { userDataPath, dataFile, databaseFile, exportPath }
}
async function createDatabaseBackup(
profile: ReturnType<typeof createProfile>,
profileId = 'profile-cli-recovery'
) {
const id = createProfileStateDatabaseBackupId()
const path = profileStateDatabaseBackupPath(profile.databaseFile, id)
const source = openProfileStateDatabase(join(profile.userDataPath, 'backup-source.db'), profileId)
try {
importProfileStateJson(
source.db,
JSON.stringify({
settings: {
theme: 'sqlite-recovered',
electronHttp1CompatibilityMode: true,
httpProxyUrl: 'sealed:unchanged'
},
extensionState: { retained: true }
})
)
await writeProfileStateDatabaseSnapshotAsync(source.db, path)
} finally {
source.db.close()
}
return { id, path }
}
describe('profile-state CLI recovery', () => {
beforeEach(() => {
previousExitCode = process.exitCode
@@ -201,237 +167,6 @@ describe('profile-state CLI recovery', () => {
}
})
it('prints kept and backup-restored sections returned by the bundled recovery process', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
vi.stubEnv('ORCA_APP_EXECUTABLE', '/packaged/Orca')
const result = {
profileId: 'profile-cli-recovery',
dataFile: profile.dataFile,
databaseFile: profile.databaseFile,
exportPaths: [],
backups: [],
revision: 3,
quarantineDirectory: '/quarantine',
removedDatabaseFiles: [],
storage: 'sqlite',
restoredPath: profile.databaseFile,
repairedSections: [
{ domain: 'automationRuns', source: 'current' },
{ domain: 'repos', backupId: '1-a', backupCreatedAtMs: 5 }
]
}
runProcessMock.mockResolvedValueOnce({
code: 0,
signal: null,
timedOut: false,
stdout: `starting\n${PROFILE_STATE_RECOVERY_RESULT_PREFIX}${JSON.stringify({ ok: true, result })}\n`,
stderr: ''
})
await main(['profile', 'state', 'rollback', '--repair'], profile.userDataPath)
expect(process.exitCode).toBe(0)
expect(runProcessMock).toHaveBeenCalledOnce()
const output = String(vi.mocked(console.log).mock.calls.at(-1)?.[0])
expect(output).toContain('repaired automationRuns: current runs kept')
expect(output).toContain(
`repaired repos: from backup 1-a saved ${new Date(5).toLocaleString()}`
)
})
it('restores the selected export through the offline CLI command', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
await main(['profile', 'state', 'rollback', '--revision', '1', '--json'], profile.userDataPath)
expect(existsSync(profile.databaseFile)).toBe(false)
expect(readFileSync(profile.dataFile, 'utf8')).toBe(
JSON.stringify({ settings: { theme: 'recovered', electronHttp1CompatibilityMode: true } })
)
expect(
JSON.parse(readFileSync(join(profile.userDataPath, 'http1-compatibility.json'), 'utf8'))
).toMatchObject({
enabled: true,
profileId: 'profile-cli-recovery'
})
const output = vi.mocked(console.log).mock.calls.at(-1)?.[0]
expect(String(output)).toContain('quarantineDirectory')
expect(getCliStatusMock).toHaveBeenCalledOnce()
})
it('adopts current JSON through CLI with an honest source description', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
const original = readFileSync(profile.dataFile)
await main(['profile', 'state', 'rollback', '--current-json'], profile.userDataPath)
expect(readFileSync(profile.dataFile)).toEqual(original)
expect(existsSync(profile.databaseFile)).toBe(false)
const output = String(vi.mocked(console.log).mock.calls.at(-1)?.[0])
expect(output).toContain('source: current JSON')
expect(output).not.toContain('revision:')
})
it('keeps current SQLite through CLI and rewrites the diverged JSON', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
rmSync(profile.databaseFile)
rmSync(`${profile.databaseFile}-wal`)
rmSync(profile.exportPath)
const source = openProfileStateDatabase(profile.databaseFile, 'profile-cli-recovery')
try {
importProfileStateJson(source.db, JSON.stringify({ settings: { theme: 'sqlite' } }))
} finally {
source.db.close()
}
writeFileSync(profile.dataFile, JSON.stringify({ settings: { theme: 'older-build' } }))
await main(['profile', 'state', 'rollback', '--current-sqlite'], profile.userDataPath)
expect(JSON.parse(readFileSync(profile.dataFile, 'utf8'))).toEqual({
settings: { theme: 'sqlite' }
})
const retained = openProfileStateDatabaseReadOnly(profile.databaseFile, 'profile-cli-recovery')
try {
expect(JSON.parse(exportProfileStateJson(retained.db))).toEqual({
settings: { theme: 'sqlite' }
})
} finally {
retained.db.close()
}
expect(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])).toContain(
'source: current SQLite'
)
})
it('refuses to keep an unreadable SQLite and leaves JSON untouched', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
const json = readFileSync(profile.dataFile)
await main(['profile', 'state', 'rollback', '--current-sqlite', '--json'], profile.userDataPath)
expect(process.exitCode).toBe(1)
expect(readFileSync(profile.dataFile)).toEqual(json)
expect(readFileSync(profile.databaseFile, 'utf8')).toBe('damaged sqlite primary')
})
it.each([
['--current-json', '--revision', '1'],
['--current-json', '--backup', '1'],
['--current-json', '--current-sqlite'],
['--current-json=false'],
['--current-sqlite=false'],
['--latest-json', '--revision', '1'],
['--latest-json', '--backup', '1'],
['--latest-json', '--current-json'],
['--latest-json', '--current-sqlite'],
['--latest-json=false']
])('rejects ambiguous recovery arguments: %s', async (...flags) => {
getCliStatusMock.mockClear()
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
await main(['profile', 'state', 'rollback', ...flags, '--json'], profile.userDataPath)
expect(process.exitCode).toBe(1)
expect(existsSync(profile.databaseFile)).toBe(true)
expect(getCliStatusMock).not.toHaveBeenCalled()
})
it('keeps profile-state recovery local when remote selection is configured', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
vi.stubEnv('ORCA_PAIRING_CODE', 'remote-pairing-code')
vi.stubEnv('ORCA_ENVIRONMENT', 'stale-environment')
await main(['profile', 'state', 'rollback', '--revision', '1', '--json'], profile.userDataPath)
expect(runtimeClientConstructorMock).toHaveBeenCalledWith(null, null)
expect(vi.mocked(console.log).mock.calls.at(-1)?.[0]).toContain('quarantineDirectory')
})
it.each([true, false])(
'recovers an absent database and archives every export (legacy JSON present: %s)',
async (hasJson) => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
rmSync(profile.databaseFile)
rmSync(`${profile.databaseFile}-wal`)
if (!hasJson) {
rmSync(profile.dataFile)
}
const laterExport = profileStateJsonExportPath(profile.dataFile, 2)
writeFileSync(laterExport, JSON.stringify({ settings: { theme: 'later' } }))
const selectedBytes = readFileSync(profile.exportPath)
const laterBytes = readFileSync(laterExport)
await main(
['profile', 'state', 'rollback', '--revision', '1', '--json'],
profile.userDataPath
)
expect(process.exitCode).toBe(0)
expect(readFileSync(profile.dataFile)).toEqual(selectedBytes)
expect(existsSync(profile.exportPath)).toBe(false)
expect(existsSync(laterExport)).toBe(false)
const output: unknown = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))
expect(output).toMatchObject({ ok: true, result: { removedDatabaseFiles: [] } })
if (
!output ||
typeof output !== 'object' ||
!('result' in output) ||
!output.result ||
typeof output.result !== 'object' ||
!('quarantineDirectory' in output.result) ||
typeof output.result.quarantineDirectory !== 'string'
) {
throw new Error('Expected rollback archive directory')
}
const archive = output.result.quarantineDirectory
expect(readFileSync(join(archive, basename(profile.exportPath)))).toEqual(selectedBytes)
expect(readFileSync(join(archive, basename(laterExport)))).toEqual(laterBytes)
expect(existsSync(join(archive, basename(profile.dataFile)))).toBe(hasJson)
expect(readPersistedHttp1CompatibilityMode(profile.userDataPath)).toBe(true)
}
)
it('preserves all live recovery sources when archiving an export fails', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
const unavailableExport = profileStateJsonExportPath(profile.dataFile, 2)
mkdirSync(unavailableExport)
const sources = [
profile.dataFile,
profile.exportPath,
profile.databaseFile,
`${profile.databaseFile}-wal`
]
const original = sources.map((path) => readFileSync(path))
await main(['profile', 'state', 'rollback', '--revision', '1', '--json'], profile.userDataPath)
expect(process.exitCode).toBe(1)
expect(sources.map((path) => readFileSync(path))).toEqual(original)
})
it('falls back to restored settings when refreshing the marker fails', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
http1Marker.writeHttp1CompatibilityMarker(profile.userDataPath, false, 'profile-cli-recovery')
const writeFileDurableSync = durableFileWrite.writeFileDurableSync
vi.spyOn(durableFileWrite, 'writeFileDurableSync').mockImplementation(
(tmp, target, contents) => {
if (target === join(profile.userDataPath, http1Marker.HTTP1_COMPATIBILITY_MARKER_FILE)) {
throw new Error('injected marker write failure')
}
return writeFileDurableSync(tmp, target, contents)
}
)
await main(['profile', 'state', 'rollback', '--revision', '1', '--json'], profile.userDataPath)
expect(existsSync(profile.databaseFile)).toBe(false)
expect(
http1Marker.readHttp1CompatibilityMarker(profile.userDataPath, 'profile-cli-recovery')
).toBeNull()
expect(readPersistedHttp1CompatibilityMode(profile.userDataPath)).toBe(true)
expect(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])).toContain('quarantineDirectory')
})
it('preserves SQLite authority when the old marker cannot be invalidated', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
@@ -450,189 +185,4 @@ describe('profile-state CLI recovery', () => {
)
expect(process.exitCode).toBe(1)
})
it('does not invalidate the active setting for an invalid recovery export', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
http1Marker.writeHttp1CompatibilityMarker(profile.userDataPath, true, 'profile-cli-recovery')
writeFileSync(profile.exportPath, 'invalid JSON')
await main(['profile', 'state', 'rollback', '--revision', '1', '--json'], profile.userDataPath)
expect(existsSync(profile.databaseFile)).toBe(true)
expect(
http1Marker.readHttp1CompatibilityMarker(profile.userDataPath, 'profile-cli-recovery')
).toBe(true)
expect(process.exitCode).toBe(1)
})
it('rejects an explicit remote selector instead of silently ignoring it', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
await main(
['profile', 'state', 'rollback', '--revision', '1', '--environment', 'remote', '--json'],
profile.userDataPath
)
expect(existsSync(profile.databaseFile)).toBe(true)
expect(vi.mocked(console.log).mock.calls.at(-1)?.[0]).toContain(
'`--environment` does not retarget profile-state recovery'
)
})
it.each([['--revision', '1'], ['--current-json'], ['--latest-json']])(
'refuses rollback while runtime is reachable: %s',
async (...flags) => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
getCliStatusMock.mockResolvedValueOnce({
id: 'status',
ok: true,
result: {
app: { running: false, pid: null },
runtime: { state: 'ready', reachable: true, runtimeId: 'headless' },
graph: { state: 'ready' }
},
_meta: { runtimeId: 'test' }
})
await main(['profile', 'state', 'rollback', ...flags], profile.userDataPath)
expect(existsSync(profile.databaseFile)).toBe(true)
expect(readFileSync(profile.dataFile, 'utf8')).toBe(
JSON.stringify({ settings: { theme: 'old' } })
)
expect(vi.mocked(console.error).mock.calls.at(-1)?.[0]).toContain('Stop Orca')
}
)
it('lists SQLite backups alongside JSON exports without opening the damaged primary', async () => {
const profile = createProfile()
const backup = await createDatabaseBackup(profile)
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
getCliStatusMock.mockClear()
await main(['profile', 'state', 'exports', '--json'], profile.userDataPath)
const output: unknown = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))
expect(output).toMatchObject({
ok: true,
result: { exportPaths: [profile.exportPath], backups: [{ id: backup.id, path: backup.path }] }
})
expect(getCliStatusMock).not.toHaveBeenCalled()
})
it.each([true, false])(
'restores SQLite backup authority with damaged database present=%s',
async (hasDatabase) => {
const profile = createProfile()
const backup = await createDatabaseBackup(profile)
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
http1Marker.writeHttp1CompatibilityMarker(profile.userDataPath, false, 'profile-cli-recovery')
if (!hasDatabase) {
rmSync(profile.databaseFile)
rmSync(`${profile.databaseFile}-wal`)
rmSync(profile.dataFile)
}
await main(
['profile', 'state', 'rollback', '--backup', backup.id, '--json'],
profile.userDataPath
)
expect(process.exitCode).toBe(0)
expect(existsSync(profile.dataFile)).toBe(false)
expect(existsSync(backup.path)).toBe(true)
const restored = openProfileStateDatabaseReadOnly(
profile.databaseFile,
'profile-cli-recovery'
)
try {
expect(JSON.parse(exportProfileStateJson(restored.db))).toMatchObject({
settings: { theme: 'sqlite-recovered', httpProxyUrl: 'sealed:unchanged' },
extensionState: { retained: true }
})
} finally {
restored.db.close()
}
expect(
http1Marker.readHttp1CompatibilityMarker(profile.userDataPath, 'profile-cli-recovery')
).toBe(true)
expect(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])).toContain('"storage": "sqlite"')
}
)
it('rejects a backup belonging to another profile before invalidating the startup marker', async () => {
const profile = createProfile()
const backup = await createDatabaseBackup(profile, 'foreign-profile')
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
http1Marker.writeHttp1CompatibilityMarker(profile.userDataPath, true, 'profile-cli-recovery')
await main(
['profile', 'state', 'rollback', '--backup', backup.id, '--json'],
profile.userDataPath
)
expect(process.exitCode).toBe(1)
expect(readFileSync(profile.databaseFile, 'utf8')).toBe('damaged sqlite primary')
expect(
http1Marker.readHttp1CompatibilityMarker(profile.userDataPath, 'profile-cli-recovery')
).toBe(true)
})
it('requires an unambiguous retained backup selection', async () => {
const profile = createProfile()
const backup = await createDatabaseBackup(profile)
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
await main(
['profile', 'state', 'rollback', '--backup', backup.id, '--revision', '1', '--json'],
profile.userDataPath
)
expect(process.exitCode).toBe(1)
expect(readFileSync(profile.databaseFile, 'utf8')).toBe('damaged sqlite primary')
expect(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])).toContain('exactly one')
})
it('rejects escaping backup IDs without touching any recovery artifact', async () => {
const profile = createProfile()
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
const sources = [
profile.dataFile,
profile.exportPath,
profile.databaseFile,
`${profile.databaseFile}-wal`
]
const original = sources.map((path) => readFileSync(path))
await main(
['profile', 'state', 'rollback', '--backup', '../../outside', '--json'],
profile.userDataPath
)
expect(process.exitCode).toBe(1)
expect(readFileSync(profile.databaseFile, 'utf8')).toBe('damaged sqlite primary')
expect(sources.map((path) => readFileSync(path))).toEqual(original)
expect(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])).toContain('backup is unavailable')
})
it('refuses database backup restoration while the app is running', async () => {
const profile = createProfile()
const backup = await createDatabaseBackup(profile)
getDefaultUserDataPathMock.mockReturnValue(profile.userDataPath)
getCliStatusMock.mockResolvedValueOnce({
result: { app: { running: true }, runtime: { reachable: false } }
})
await main(
['profile', 'state', 'rollback', '--backup', backup.id, '--json'],
profile.userDataPath
)
expect(process.exitCode).toBe(1)
expect(readFileSync(profile.databaseFile, 'utf8')).toBe('damaged sqlite primary')
expect(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])).toContain('Stop Orca')
})
})
@@ -1,18 +1,9 @@
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
renameSync,
rmSync,
writeFileSync
} from 'node:fs'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createServer, type Socket } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { setAppEnvironment } from '../../shared/app-environment'
import { readAgentHookSettingsFromProfileState } from '../../main/persistence/profile-state/offline-access/profile-state-offline-settings'
import type * as ProcessHost from '@orca/process-host'
import { main } from '../index'
@@ -119,78 +110,10 @@ function metadata(shape = 'complete', pid = 2147483647) {
})
)
}
function settings() {
return readAgentHookSettingsFromProfileState({
dataFile: join(profile, 'orca-data.json'),
databaseFile: join(profile, 'profile-state.db'),
profileId: 'fixture'
})
}
function output() {
return JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))
}
async function refusedEndpoint() {
const listener = createServer()
await new Promise<void>((resolve) => listener.listen(endpoint, resolve))
renameSync(endpoint, `${endpoint}.stale`)
await new Promise<void>((resolve) => listener.close(() => resolve()))
renameSync(`${endpoint}.stale`, endpoint)
}
describe.skipIf(process.platform === 'win32')(
'offline CLI admission through dispatch and persistence',
() => {
it.each(['complete', 'singular', 'incomplete', 'refused'])(
'recovers JSON and toggles hooks both ways with %s stopped metadata',
async (shape) => {
metadata(shape)
if (shape === 'refused') {
await refusedEndpoint()
}
await main(['profile', 'state', 'rollback', '--current-json', '--json'], root)
expect(process.exitCode).toBe(0)
expect(output()).toMatchObject({ ok: true, result: { storage: 'json' } })
expect(JSON.parse(readFileSync(join(profile, 'orca-data.json'), 'utf8'))).toMatchObject({
retained: { value: 7 }
})
for (const enabled of [true, false]) {
await main(['agent', 'hooks', enabled ? 'on' : 'off', '--json'], root)
expect(process.exitCode).toBe(0)
expect(output()).toMatchObject({
ok: true,
result: {
enabled,
appliedBy: 'offline',
statuses: [expect.objectContaining({ agent: 'claude', managedHooksPresent: enabled })]
}
})
expect(settings().agentStatusHooksEnabled).toBe(enabled)
const config = JSON.parse(
readFileSync(join(root, 'HOME', '.claude', 'settings.json'), 'utf8')
)
expect(JSON.stringify(config.hooks ?? {}).includes('orca')).toBe(enabled)
}
}
)
it('refuses a visible PID without creating a database or changing profile and hook files', async () => {
metadata('complete', process.pid)
const before = readFileSync(join(profile, 'orca-data.json'))
for (const args of [
['profile', 'state', 'rollback', '--current-json'],
['agent', 'hooks', 'on'],
['agent', 'hooks', 'off']
]) {
process.exitCode = 0
await main([...args, '--json'], root)
expect(process.exitCode).toBe(1)
expect(output()).toMatchObject({ ok: false, error: { code: 'runtime_error' } })
expect(readFileSync(join(profile, 'orca-data.json'))).toEqual(before)
expect(existsSync(join(profile, 'profile-state.db'))).toBe(false)
expect(existsSync(join(root, 'HOME', '.claude'))).toBe(false)
}
})
it.each(['close', 'server-error'])(
'never replays a failed online settings update offline (%s)',
async (failure) => {
@@ -61,17 +61,6 @@ describe('Claude permission hook channel', () => {
expect(held.ends).toEqual([])
})
it('passes with {} when the budget runs out or Orca quits', async () => {
const timedOut = await holdOne(20)
expect(await timedOut.reply).toBe('{}')
expect(timedOut.ends).toEqual(['budget'])
const quit = await holdOne(60_000)
quit.channel.drain()
expect(await quit.reply).toBe('{}')
expect(quit.ends).toEqual(['quit'])
})
it('reports a hook that hung up before any answer', async () => {
const held = await holdOne(60_000)
held.hang()
@@ -1,81 +0,0 @@
import '../worker/session-search-worker.test-fixture'
import { mkdir, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it } from 'vitest'
import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers'
import { retireDeletedSessionSearchSources } from './session-search-deleted-sources'
import {
SessionSearchDirectoryListings,
type SessionSearchDirectoryReader
} from './session-search-directory-listings'
import {
openSessionSearchIndexerHarness,
type SessionSearchIndexerHarness
} from '../indexing/session-search-indexer-test-fixture'
import { SessionSearchStore } from '../storage/session-search-store'
let harness: SessionSearchIndexerHarness
let store: SessionSearchStore
let removed: string[]
beforeEach(async () => {
resetTranscriptConsumersForTests()
harness = await openSessionSearchIndexerHarness('ss-deleted-sources')
removed = []
store = new SessionSearchStore(harness.databasePath)
store.removeFile = (path: string) => removed.push(path)
})
afterEach(async () => {
store.close()
await harness.cleanup()
})
function retire(
paths: readonly string[],
options: {
roots?: readonly string[]
emptiedRoots?: ReadonlySet<string>
enumeratedContainers?: ReadonlyMap<string, ReadonlySet<string>>
listings?: SessionSearchDirectoryReader
directoryLimit?: number
} = {}
) {
return retireDeletedSessionSearchSources({
store,
paths,
roots: options.roots ?? [harness.roots.claudeProjectsDir ?? ''],
emptiedRoots: options.emptiedRoots,
enumeratedContainers: options.enumeratedContainers,
listings: options.listings ?? new SessionSearchDirectoryListings(),
directoryLimit: options.directoryLimit
})
}
it('judges each merged-root directory on its own', async () => {
const current = join(harness.roots.openclawStateDir ?? '', 'agents')
const legacy = join(harness.roots.openclawLegacyStateDir ?? '', 'agents')
const onMissing = join(current, 'main', 'sessions', 'mounted.jsonl')
const deleted = join(legacy, 'main', 'sessions', 'deleted.jsonl')
await mkdir(join(legacy, 'main', 'sessions'), { recursive: true })
const result = await retire([onMissing, deleted], { roots: [current, legacy] })
expect(result.retired).toEqual([deleted])
expect(result.unverifiable).toEqual([onMissing])
expect(result.degradedRoots.map((one) => one.root)).toEqual([current])
})
it('retires a synthetic row when the container it came from is gone', async () => {
const db = join(harness.root, 'opencode.db')
await writeFile(db, '')
const row = `${db}#session-1`
const enumeratedContainers = new Map([[db, new Set(['session-1'])]])
await expect(retire([row], { roots: [], enumeratedContainers })).resolves.toMatchObject({
retired: []
})
await rm(db)
await expect(retire([row], { roots: [], enumeratedContainers })).resolves.toMatchObject({
retired: [row]
})
})
@@ -1,22 +0,0 @@
import { beforeEach, expect, it, vi } from 'vitest'
import { SessionSearchDirectoryListings } from './session-search-directory-listings'
const { readdir } = vi.hoisted(() => ({ readdir: vi.fn() }))
vi.mock('../../native-chat/wsl-transcript-fs-access', () => ({
wslGatedReaddir: readdir
}))
beforeEach(() => {
readdir.mockReset()
})
it('reports the code a failed read carried, so ENOENT and EACCES stay apart', async () => {
readdir.mockRejectedValueOnce(Object.assign(new Error('permission denied'), { code: 'EACCES' }))
const listings = new SessionSearchDirectoryListings()
expect(await listings.namesIn('/blocked')).toEqual({
listed: false,
code: 'EACCES',
message: 'permission denied'
})
})
@@ -1,53 +0,0 @@
import { expect, it } from 'vitest'
import { delimiter, join } from 'node:path'
import type { SessionFileDiscovery } from '../../ai-vault/session-scanner-types'
import { sameSessionSearchRoots, sessionSearchRootListings } from './session-search-scan-roots'
const STATE = '/tmp/ss-roots/openclaw-state'
const LEGACY = '/tmp/ss-roots/openclaw-legacy'
function file(path: string): SessionFileDiscovery['files'][number] {
return { path, mtimeMs: 0, modifiedAt: new Date(0).toISOString() }
}
it('attributes a file by path segment, not by string prefix', () => {
const agents = join(STATE, 'agents')
const legacy = join(LEGACY, 'agents')
const listings = sessionSearchRootListings(
{ openclawStateDir: STATE, openclawLegacyStateDir: LEGACY },
[
{
agent: 'openclaw',
rootDir: [agents, legacy].join(delimiter),
files: [file(join(`${agents}-old`, 'b', 'sessions', 'two.jsonl'))]
}
]
)
const byRoot = Object.fromEntries(listings.map((one) => [one.root, one.files]))
expect(byRoot[agents]).toBe(0)
expect(byRoot[legacy]).toBe(0)
})
it('compares WSL readers structurally without restarting for reordered objects', () => {
const ubuntu = { distro: 'Ubuntu', executable: '/usr/bin/node', readerPath: '/reader.cjs' }
const debian = { distro: 'Debian', error: 'Preparing' }
expect(
sameSessionSearchRoots(
{ wslOpenCodeReaders: [ubuntu, debian] },
{
wslOpenCodeReaders: [
{ error: 'Preparing', distro: 'debian' },
{ readerPath: '/reader.cjs', executable: '/usr/bin/node', distro: 'ubuntu' }
]
}
)
).toBe(true)
expect(sameSessionSearchRoots({}, { wslOpenCodeReaders: [] })).toBe(true)
expect(
sameSessionSearchRoots(
{ wslOpenCodeReaders: [ubuntu] },
{ wslOpenCodeReaders: [{ ...ubuntu, executable: '/new/node' }] }
)
).toBe(false)
})
@@ -1,6 +1,6 @@
import '../worker/session-search-worker.test-fixture'
import 'node:fs'
import { appendFile, chmod, mkdir, rm, stat, utimes } from 'node:fs/promises'
import { rm, stat } from 'node:fs/promises'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it } from 'vitest'
import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store'
@@ -8,10 +8,7 @@ import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/ses
import type SyncDatabase from '../../sqlite/sync-database'
import { SessionSearchIndexer } from './session-search-indexer'
import '../storage/session-search-schema'
import { removeVersionedCacheDatabase } from '../../sqlite/versioned-cache-database'
import { parseTranscript } from './session-search-transcript-fixtures'
import {
claudeLines,
FakeSessionSearchClock,
openSessionSearchIndexerHarness,
renameReplaceTranscript,
@@ -20,11 +17,7 @@ import {
} from './session-search-indexer-test-fixture'
const INTERVAL_MS = 20_000
// chmod cannot deny reads to root or reliably enforce mode bits on Windows.
const CAN_DENY_READ = process.platform !== 'win32' && process.getuid?.() !== 0
const SESSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
const OTHER_SESSION_ID = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff'
const SETTLED_SESSION_ID = 'dddddddd-cccc-4ddd-8eee-ffffffffffff'
let harness: SessionSearchIndexerHarness
let clock: FakeSessionSearchClock
@@ -77,86 +70,15 @@ function sessionsMatching(term: string): string[] {
)
}
function rowFor(path: string) {
return harness.read((db: SyncDatabase) =>
db.prepare('SELECT state, fail_count AS failCount FROM files WHERE path = ?').get(path)
) as { state: string; failCount: number } | undefined
}
function fileState(path: string): string | undefined {
return rowFor(path)?.state
}
function indexedByteOffset(path: string): number | undefined {
return harness.read(
(db: SyncDatabase) =>
(
db.prepare('SELECT byte_offset AS offset FROM files WHERE path = ?').get(path) as
| { offset: number }
| undefined
)?.offset
)
}
function plantPartialCursor(path: string): void {
harness.write((db: SyncDatabase) =>
db.prepare('UPDATE files SET byte_offset = -1 WHERE path = ?').run(path)
)
}
function indexedCursor(path: string): { mtime_ms: number; size_bytes: number } | undefined {
return harness.read(
(db: SyncDatabase) =>
db.prepare('SELECT mtime_ms, size_bytes FROM files WHERE path = ?').get(path) as
| { mtime_ms: number; size_bytes: number }
| undefined
)
}
function transcriptPath(name = SESSION_ID): string {
return join(harness.claudeProjectDir, `${name}.jsonl`)
}
/** Pre-index a future-dated transcript so later cycles skip it but keep it in the recency window. */
async function startAfterASweep(
overrides: Partial<ConstructorParameters<typeof SessionSearchIndexer>[0]> = {}
): Promise<void> {
const settled = transcriptPath(SETTLED_SESSION_ID)
await writeClaudeTranscript(settled, ['a conversation from before'], SETTLED_SESSION_ID)
// Recency uses real file mtimes rather than the fake retention clock.
const ahead = new Date(Date.now() + 3_600_000)
await utimes(settled, ahead, ahead)
await newIndexer(overrides).start()
}
/** Spend one fake second per clock check to limit each pass to the requested number of reads. */
function readsPerPass(files: number): { passDeadlineMs: number } {
clock.costPerNowMs = 1_000
return { passDeadlineMs: files * 1_000 }
}
async function nextCycle(): Promise<void> {
clock.advance(INTERVAL_MS)
await indexer?.settled()
}
it('reflects a grown transcript within one reconcile interval', async () => {
const path = transcriptPath()
await writeClaudeTranscript(path, ['find the flaky terminal reattach'], SESSION_ID)
await newIndexer().start()
expect(sessionsMatching('reattach')).toEqual([SESSION_ID])
expect(sessionsMatching('quarantine')).toEqual([])
await appendFile(
path,
`${claudeLines(['quarantine the leaking pty'], SESSION_ID, 10).join('\n')}\n`
)
await nextCycle()
expect(sessionsMatching('quarantine')).toEqual([SESSION_ID])
expect(errors).toEqual([])
})
it('reflects a rename-replaced transcript within one reconcile interval', async () => {
const path = transcriptPath()
await writeClaudeTranscript(path, ['original content aaaa'], SESSION_ID)
@@ -173,188 +95,6 @@ it('reflects a rename-replaced transcript within one reconcile interval', async
expect(errors).toEqual([])
})
it('retires a deleted transcript within one reconcile interval', async () => {
const path = transcriptPath()
await writeClaudeTranscript(path, ['a session about to be deleted'], SESSION_ID)
await writeClaudeTranscript(
transcriptPath(OTHER_SESSION_ID),
['a surviving session'],
OTHER_SESSION_ID
)
await newIndexer().start()
await nextCycle()
expect(sessionsMatching('deleted')).toEqual([SESSION_ID])
await rm(path)
await nextCycle()
expect(sessionsMatching('deleted')).toEqual([])
expect(sessionsMatching('surviving')).toEqual([OTHER_SESSION_ID])
})
it('widens history by constructing a new instance and narrows by purging on its first sweep', async () => {
const fresh = transcriptPath()
const old = transcriptPath(OTHER_SESSION_ID)
await writeClaudeTranscript(fresh, ['a recent conversation'], SESSION_ID)
await writeClaudeTranscript(old, ['an ancient conversation'], OTHER_SESSION_ID)
const longAgo = new Date(clock.now() - 120 * 86_400_000)
await utimes(old, longAgo, longAgo)
// Keep the older transcript outside the recent cycle window so only a sweep can admit it.
await newIndexer({ historyDays: 30, recentPerAgent: 1 }).start()
expect(sessionsMatching('recent')).toEqual([SESSION_ID])
expect(sessionsMatching('ancient')).toEqual([])
await indexer?.close()
await newIndexer({ historyDays: null, recentPerAgent: 1 }).start()
expect(sessionsMatching('ancient')).toEqual([OTHER_SESSION_ID])
await indexer?.close()
await newIndexer({ historyDays: 30, recentPerAgent: 1 }).start()
expect(sessionsMatching('ancient')).toEqual([])
expect(sessionsMatching('recent')).toEqual([SESSION_ID])
})
it.skipIf(!CAN_DENY_READ)(
'names an unreadable root as degraded and keeps indexing the others',
async () => {
const blocked = join(harness.roots.codexSessionsDir ?? '', 'blocked')
await mkdir(blocked, { recursive: true })
await writeClaudeTranscript(transcriptPath(), ['a readable claude session'], SESSION_ID)
await chmod(harness.roots.codexSessionsDir ?? '', 0o000)
try {
await newIndexer().start()
const status = indexer?.status()
expect(status?.phase).toBe('degraded')
expect(status?.degradedRoots.map((root) => root.root)).toContain(
harness.roots.codexSessionsDir
)
expect(status?.degradedRoots[0]?.reason).toBeTruthy()
expect(sessionsMatching('readable')).toEqual([SESSION_ID])
} finally {
await chmod(harness.roots.codexSessionsDir ?? '', 0o755)
}
}
)
it('fills an empty index over a warm session-list cache on the first reconcile', async () => {
await startAfterASweep()
const path = transcriptPath()
await writeClaudeTranscript(path, ['scanned before the index existed'], SESSION_ID)
await parseTranscript(path)
await indexer?.reconcile()
expect(sessionsMatching('scanned')).toEqual([SESSION_ID])
})
it('moves the retention window with the clock instead of freezing it at construction', async () => {
const path = transcriptPath()
await writeClaudeTranscript(path, ['an entry that ages out'], SESSION_ID)
const now = new Date(clock.now())
await utimes(path, now, now)
await newIndexer({ historyDays: 1 }).start()
expect(sessionsMatching('ages')).toEqual([SESSION_ID])
clock.advance(3 * 86_400_000)
await indexer?.reconcile({ full: true })
expect(sessionsMatching('ages')).toEqual([])
await nextCycle()
expect(sessionsMatching('ages')).toEqual([])
})
it('re-reads a file a chunked read left half written, and settles it in one pass', async () => {
const path = transcriptPath()
await writeClaudeTranscript(path, ['the committed half'], SESSION_ID)
await newIndexer().start()
const whole = (await stat(path)).size
expect(indexedByteOffset(path)).toBe(whole)
await indexer?.close()
plantPartialCursor(path)
await newIndexer().start()
expect(indexedByteOffset(path)).toBe(whole)
expect(fileState(path)).toBe('current')
expect(indexer?.status().phase).toBe('current')
await indexer?.close()
// Growing a partially indexed file must force a whole read rather than offer a declined append.
plantPartialCursor(path)
await appendFile(path, `${claudeLines(['the lost half'], SESSION_ID, 10).join('\n')}\n`)
await newIndexer().start()
expect(sessionsMatching('lost')).toEqual([SESSION_ID])
expect(indexer?.status()).toMatchObject({ filesDue: 0, phase: 'current' })
})
it('reads a deferred file at its current stat, not the one the pass first saw', async () => {
await startAfterASweep(readsPerPass(1))
const older = transcriptPath(OTHER_SESSION_ID)
await writeClaudeTranscript(older, ['the deferred conversation'], OTHER_SESSION_ID)
await writeClaudeTranscript(transcriptPath(), ['the newer conversation'], SESSION_ID)
const ahead = new Date((await stat(transcriptPath())).mtimeMs + 60_000)
await utimes(transcriptPath(), ahead, ahead)
await indexer?.reconcile()
expect(rowFor(older)).toBeUndefined()
await appendFile(
older,
`${claudeLines(['appended while deferred'], OTHER_SESSION_ID, 10).join('\n')}\n`
)
await indexer?.reconcile()
expect(sessionsMatching('appended')).toEqual([OTHER_SESSION_ID])
const cursor = indexedCursor(older)
const current = await stat(older)
expect(cursor).toEqual({ mtime_ms: current.mtimeMs, size_bytes: current.size })
})
it('reads a declined file at its current stat, not the one it was recorded with', async () => {
const path = transcriptPath()
await writeClaudeTranscript(path, ['the recorded conversation'], SESSION_ID)
await newIndexer().start()
// Retain the session-list cursor while deleting the index to force an append the consumer must decline.
await indexer?.close()
removeVersionedCacheDatabase(harness.databasePath)
newIndexer()
await appendFile(path, `${claudeLines(['declined turn'], SESSION_ID, 10).join('\n')}\n`)
await parseTranscript(path)
expect(indexer?.status().filesIndexed).toBe(0)
await appendFile(path, `${claudeLines(['later turn'], SESSION_ID, 20).join('\n')}\n`)
await indexer?.start()
await nextCycle()
expect(sessionsMatching('later')).toEqual([SESSION_ID])
const current = await stat(path)
expect(indexedCursor(path)).toEqual({ mtime_ms: current.mtimeMs, size_bytes: current.size })
})
it.skipIf(!CAN_DENY_READ)(
'keeps an unlistable root through the cycles that follow the sweep',
async () => {
await writeClaudeTranscript(transcriptPath(), ['a session on a removable volume'], SESSION_ID)
await newIndexer().start()
expect(sessionsMatching('removable')).toEqual([SESSION_ID])
await chmod(harness.roots.claudeProjectsDir ?? '', 0o000)
try {
await indexer?.reconcile({ full: true })
expect(sessionsMatching('removable')).toEqual([SESSION_ID])
await nextCycle()
expect(sessionsMatching('removable')).toEqual([SESSION_ID])
expect(indexer?.status().phase).toBe('degraded')
} finally {
await chmod(harness.roots.claudeProjectsDir ?? '', 0o755)
}
}
)
it('keeps a root that is gone at the first sweep after a restart', async () => {
await writeClaudeTranscript(transcriptPath(), ['a session on a removable volume'], SESSION_ID)
await newIndexer().start()
@@ -374,71 +114,3 @@ it('keeps a root that is gone at the first sweep after a restart', async () => {
await indexer?.reconcile({ full: true })
expect(indexer?.status()).toMatchObject({ phase: 'current', degradedRoots: [] })
})
// An unmounted root that remains readable and empty is indistinguishable from intentional deletion.
it('retires an emptied configured root, one pass after it emptied', async () => {
await writeClaudeTranscript(transcriptPath(), ['a session on the mounted volume'], SESSION_ID)
await newIndexer().start()
await rm(harness.claudeProjectDir, { recursive: true, force: true })
await indexer?.reconcile({ full: true })
expect(sessionsMatching('mounted')).toEqual([SESSION_ID])
expect(indexer?.status().phase).toBe('degraded')
await indexer?.reconcile({ full: true })
expect(sessionsMatching('mounted')).toEqual([])
expect(indexer?.status()).toMatchObject({ phase: 'current', degradedRoots: [] })
})
// A missing configured root prevents retirement even when its parent is readable and empty.
it('keeps rows under no configured root, and retires them only when gone', async () => {
const moved = transcriptPath()
await writeClaudeTranscript(moved, ['a session in the old profile'], SESSION_ID)
await newIndexer().start()
await indexer?.close()
resetTranscriptConsumersForTests()
resetSessionParseCacheForTests()
const elsewhere = join(harness.root, 'moved-profile')
newIndexer({ roots: { ...harness.roots, claudeProjectsDir: elsewhere } })
await indexer?.start()
expect(sessionsMatching('profile')).toEqual([SESSION_ID])
await rm(moved)
await indexer?.reconcile({ full: true })
expect(sessionsMatching('profile')).toEqual([])
})
it.skipIf(!CAN_DENY_READ)('retires a deleted file behind a block of unreadable rows', async () => {
// Keep the root nonempty so empty-root grace cannot mask retirement behavior.
await writeClaudeTranscript(transcriptPath(), ['a live conversation'], SESSION_ID)
const locked = join(harness.roots.claudeProjectsDir ?? '', 'locked')
await mkdir(locked, { recursive: true })
await newIndexer().initialize()
// Put 520 unreadable rows ahead of the deleted row to catch limits counted by rows instead of directories.
harness.write((db: SyncDatabase) => {
const insert = db.prepare(
`INSERT INTO files(path, byte_offset, mtime_ms, size_bytes, state)
VALUES (?, 0, ?, 10, 'current')`
)
for (let index = 0; index < 520; index++) {
insert.run(join(locked, `locked-${index}.jsonl`), 1_700_000_000_000 + index)
}
return insert.run(join(harness.claudeProjectDir, 'deleted.jsonl'), 1_700_000_999_000)
})
const deleted = join(harness.claudeProjectDir, 'deleted.jsonl')
const holdsDeleted = (): boolean => rowFor(deleted) !== undefined
await chmod(locked, 0o000)
try {
await indexer?.start()
expect(holdsDeleted()).toBe(false)
expect(indexer?.status().filesIndexed).toBe(521)
expect(indexer?.status().phase).toBe('degraded')
} finally {
await chmod(locked, 0o700)
}
})
@@ -1,46 +1,10 @@
import '../../pty-subprocess/testing/mock-descendant-sweep'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { spawn } from 'node:child_process'
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { createServer, connect, type Server } from 'node:net'
import { DaemonServer } from '../../server/daemon-server'
import { getDaemonPidPath, serializeDaemonPidFile } from '../../launch/daemon-spawner'
import {
checkDaemonHealth,
checkDaemonHealthWithCoverage,
getMacDaemonSystemResolverHealth,
healthCheckDaemon
} from '../daemon-health'
import { killStaleDaemon } from '../../launch/daemon-stale-kill'
import type { SubprocessHandle } from '../../sessions/session-subprocess-handle'
import type * as ResolverHealthModule from '../../../network/macos-system-resolver-health'
import type { SystemResolverHealth } from '../../protocol/daemon-rpc-contract'
const readResolverHealthMock = vi.hoisted(() => vi.fn<() => Promise<SystemResolverHealth>>())
vi.mock('../../../network/macos-system-resolver-health', async (importOriginal) => ({
...(await importOriginal<typeof ResolverHealthModule>()),
readCurrentProcessMacSystemResolverHealth: readResolverHealthMock
}))
function createMockSubprocess(): SubprocessHandle {
return {
pid: 55555,
getForegroundProcess: () => null,
write() {},
resize() {},
kill() {},
terminateOwnedTree: () => 'unavailable' as const,
forceKill() {},
signal() {},
onData() {},
onExit() {},
dispose() {}
}
}
function closeServer(server: Server): Promise<void> {
return new Promise((resolve) => {
@@ -92,110 +56,6 @@ describe('daemon health', () => {
rmSync(dir, { recursive: true, force: true })
})
it('passes when a daemon answers ping', async () => {
const ptySpawnHealthCheck = vi.fn(async () => {})
const server = new DaemonServer({
socketPath,
tokenPath,
ptySpawnHealthCheck,
spawnSubprocess: () => createMockSubprocess()
})
await server.start()
try {
await expect(checkDaemonHealth(socketPath, tokenPath)).resolves.toBe('healthy')
await expect(healthCheckDaemon(socketPath, tokenPath)).resolves.toBe(true)
await expect(checkDaemonHealthWithCoverage(socketPath, tokenPath)).resolves.toEqual({
verdict: 'healthy',
coverage: process.platform === 'win32' ? 'handshake' : 'pty-spawn'
})
expect(ptySpawnHealthCheck).toHaveBeenCalledTimes(3)
} finally {
await server.shutdown()
}
})
it('treats missing coverage from a legacy Windows daemon as handshake-only', async () => {
writeFileSync(tokenPath, 'legacy-token')
const server = createServer((socket) => {
let pending = ''
socket.on('data', (chunk) => {
pending += chunk.toString()
for (;;) {
const newline = pending.indexOf('\n')
if (newline === -1) {
return
}
const message: unknown = JSON.parse(pending.slice(0, newline))
const type =
typeof message === 'object' && message !== null && 'type' in message
? message.type
: undefined
pending = pending.slice(newline + 1)
if (type === 'hello') {
socket.write(`${JSON.stringify({ type: 'hello', ok: true })}\n`)
} else if (type === 'ptySpawnHealth') {
socket.write(
`${JSON.stringify({ id: 'health-1', ok: true, payload: { healthy: true } })}\n`
)
}
}
})
})
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(socketPath, resolve)
})
const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
try {
await expect(checkDaemonHealthWithCoverage(socketPath, tokenPath)).resolves.toEqual({
verdict: 'healthy',
coverage: 'handshake'
})
} finally {
Object.defineProperty(process, 'platform', platform)
await closeServer(server)
}
})
it('fails when a protocol-healthy daemon cannot spawn PTYs', async () => {
const server = new DaemonServer({
socketPath,
tokenPath,
ptySpawnHealthCheck: vi.fn(async () => {
throw new Error('stale node-pty helper')
}),
spawnSubprocess: () => createMockSubprocess()
})
await server.start()
try {
await expect(checkDaemonHealth(socketPath, tokenPath)).resolves.toBe('pty-spawn-unhealthy')
await expect(healthCheckDaemon(socketPath, tokenPath)).resolves.toBe(false)
} finally {
await server.shutdown()
}
})
it('classifies a hello-rejected daemon as rejected, not unreachable', async () => {
const server = new DaemonServer({
socketPath,
tokenPath,
spawnSubprocess: () => createMockSubprocess()
})
await server.start()
try {
writeFileSync(tokenPath, 'not-the-daemon-token', { mode: 0o600 })
await expect(checkDaemonHealth(socketPath, tokenPath)).resolves.toBe('rejected')
await expect(healthCheckDaemon(socketPath, tokenPath)).resolves.toBe(false)
} finally {
await server.shutdown()
}
})
it('does not unlink a live socket when the pid file does not match this daemon', async () => {
const server = createServer((socket) => socket.end())
await new Promise<void>((resolve, reject) => {
@@ -216,107 +76,6 @@ describe('daemon health', () => {
await closeServer(server)
}
})
// The resolver probe answers 'unknown' off macOS without touching the socket.
describe.skipIf(process.platform !== 'darwin')('macOS resolver health probe', () => {
afterEach(() => {
vi.useRealTimers()
readResolverHealthMock.mockReset()
})
it('answers concurrent probes instead of evicting each other', async () => {
// Hold every answer until all three probes are live so their control sockets overlap.
const releaseProbes: (() => void)[] = []
readResolverHealthMock.mockImplementation(
() =>
new Promise((resolve) => {
releaseProbes.push(() => resolve('healthy'))
if (releaseProbes.length === 3) {
releaseProbes.forEach((release) => release())
}
})
)
const server = new DaemonServer({
socketPath,
tokenPath,
spawnSubprocess: () => createMockSubprocess()
})
await server.start()
try {
const results = await Promise.all([
getMacDaemonSystemResolverHealth(socketPath, tokenPath),
getMacDaemonSystemResolverHealth(socketPath, tokenPath),
getMacDaemonSystemResolverHealth(socketPath, tokenPath)
])
expect(results).toEqual(['healthy', 'healthy', 'healthy'])
} finally {
await server.shutdown()
}
})
it('settles as unknown when the daemon closes the probe socket', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
writeFileSync(tokenPath, 'token', { mode: 0o600 })
const server = createServer((socket) => {
socket.once('data', () => {
socket.write(`${JSON.stringify({ type: 'hello', ok: true })}\n`)
socket.once('data', () => socket.end())
})
})
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(socketPath, resolve)
})
try {
await expect(getMacDaemonSystemResolverHealth(socketPath, tokenPath)).resolves.toBe(
'unknown'
)
} finally {
await closeServer(server)
}
})
})
})
describe('killStaleDaemon pid identity guards', () => {
let dir: string
let socketPath: string
let tokenPath: string
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'daemon-health-pid-test-'))
socketPath = daemonTestSocketPath(dir)
tokenPath = join(dir, 'daemon.token')
})
afterEach(() => {
rmSync(dir, { recursive: true, force: true })
})
it('does not SIGTERM when the saved startedAtMs mismatches the current process', async () => {
const bogusStartedAtMs = Date.now() - 60 * 60 * 1000
writeFileSync(
getDaemonPidPath(dir),
serializeDaemonPidFile({ pid: process.pid, startedAtMs: bogusStartedAtMs }),
{ mode: 0o600 }
)
// Signal 0 checks liveness; only termination signals must be absent.
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
try {
await expect(killStaleDaemon(dir, socketPath, tokenPath)).resolves.toMatchObject({
killed: false
})
const terminationSignals = killSpy.mock.calls.filter(
([, sig]) => sig === 'SIGTERM' || sig === 'SIGKILL'
)
expect(terminationSignals).toEqual([])
} finally {
killSpy.mockRestore()
}
})
})
describe('killStaleDaemon ownership decisions', () => {
@@ -334,16 +93,6 @@ describe('killStaleDaemon ownership decisions', () => {
rmSync(dir, { recursive: true, force: true })
})
function listenOnSocketPath(server: Server, path: string): Promise<void> {
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(path, () => {
server.off('error', reject)
resolve()
})
})
}
it('preserves a daemon that cannot be proven dead', async () => {
const record = serializeDaemonPidFile({
pid: process.pid,
@@ -366,87 +115,4 @@ describe('killStaleDaemon ownership decisions', () => {
killSpy.mockRestore()
}
})
it.each(['{truncated', ''])('removes a malformed pid record %j', async (record) => {
writeFileSync(getDaemonPidPath(dir), record, { mode: 0o600 })
await killStaleDaemon(dir, socketPath, tokenPath, undefined, {
probeEndpoint: async () => 'missing'
})
expect(existsSync(getDaemonPidPath(dir))).toBe(false)
})
it.each(['connected', 'unknown'] as const)(
'keeps an empty pid record while its endpoint probe is %s',
async (outcome) => {
writeFileSync(getDaemonPidPath(dir), '', { mode: 0o600 })
await expect(
killStaleDaemon(dir, socketPath, tokenPath, undefined, {
probeEndpoint: async () => outcome
})
).resolves.toEqual({ killed: false, liveOwnerSurvived: true })
expect(existsSync(getDaemonPidPath(dir))).toBe(true)
}
)
it.skipIf(process.platform === 'win32')(
"leaves a replacement's pid record after killing the recorded owner",
async () => {
const child = spawn(
process.execPath,
[
'-e',
"process.on('SIGTERM', () => {}); console.log('ready'); setInterval(() => {}, 1000)",
'daemon-entry',
socketPath,
tokenPath
],
{ stdio: ['ignore', 'pipe', 'ignore'] }
)
// Wait until the child installs its SIGTERM handler so the fencing window stays open.
await new Promise<void>((resolve, reject) => {
child.once('error', reject)
child.stdout?.once('data', () => resolve())
})
const childPid = child.pid as number
const childExited = new Promise<void>((resolve) => child.once('exit', () => resolve()))
writeFileSync(
getDaemonPidPath(dir),
serializeDaemonPidFile({ pid: childPid, startedAtMs: null, launchNonce: 'daemon-a' }),
{ mode: 0o600 }
)
const replacementRecord = serializeDaemonPidFile({
pid: process.pid,
startedAtMs: 2_000,
launchNonce: 'daemon-b'
})
const replacement = createServer((socket) => socket.end())
const handover = setTimeout(() => {
void listenOnSocketPath(replacement, socketPath).then(() => {
writeFileSync(getDaemonPidPath(dir), replacementRecord, { mode: 0o600 })
})
}, 300)
try {
await expect(killStaleDaemon(dir, socketPath, tokenPath)).resolves.toEqual({
killed: true,
liveOwnerSurvived: true
})
expect(readFileSync(getDaemonPidPath(dir), 'utf8')).toBe(replacementRecord)
await expect(canConnect(socketPath)).resolves.toBe(true)
} finally {
clearTimeout(handover)
try {
process.kill(childPid, 'SIGKILL')
} catch {
// Already gone.
}
await childExited
await closeServer(replacement)
}
}
)
})
@@ -4,13 +4,8 @@ import { createRootDispatch } from '../root-dispatch-test-fixture'
import { claimTaskForStart } from '../tasks/task-start-claim'
import type { RunRow } from '../orchestration-records'
import type { OrchestrationWorkerServer } from '../../federation/environment-transport'
import {
getRemoteDispatch,
listRemoteDispatches,
oweRemoteDispatchStop
} from './remote-dispatch-records'
import { getRemoteDispatch, listRemoteDispatches } from './remote-dispatch-records'
import { importRemoteOwnedItem, type PulledRemoteOwnedItem } from './remote-owned-import'
import { refuseTaskOfClosedPairing } from './remote-placement-hold'
import {
getRemotePlacement,
recordRemoteStart,
@@ -151,27 +146,6 @@ describe('remote-owned records on the coordinating Orca', () => {
const importItem = (pulled: PulledRemoteOwnedItem) => importRemoteOwnedItem(db, PIN, pulled)
describe('a database an unreleased build made', () => {
it('repairs the placement and record tables on open, so starts and settlements work', () => {
db.db.exec(`
DROP TABLE remote_placements;
CREATE TABLE remote_placements (
task_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, environment_id TEXT NOT NULL,
conversation_id TEXT NOT NULL, state TEXT NOT NULL, request_key TEXT NOT NULL,
prior_task_status TEXT NOT NULL, dispatch_id TEXT, reserved_by_runtime TEXT NOT NULL,
outcome_unknown INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
ALTER TABLE remote_dispatches DROP COLUMN task_settled_here;
`)
db.createTables()
startedOnB('task_t', 'ctx_b1')
settleRemoteAttemptHere(db, 'ctx_b1', 'stopped')
expect(getRemoteDispatch(db, 'ctx_b1')).toMatchObject({ task_settled_here: 1 })
})
})
describe('a retry here of an attempt on the server, by the local rule', () => {
const retryHere = () => claimTaskForStart(db, db.getTask('task_t')!, { retryOf: 'ctx_b1' })
@@ -186,68 +160,6 @@ describe('remote-owned records on the coordinating Orca', () => {
settleRemoteAttemptHere(db, 'ctx_b1', 'abandoned')
expect(retryHere).not.toThrow()
})
it('follows a stop the server proved', () => {
startedOnB('task_t', 'ctx_b1')
importItem(stateItem('ctx_b1', 'task_t', { status: 'dispatched', workerState: 'ready' }))
settleRemoteAttemptHere(db, 'ctx_b1', 'stopped')
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'failed',
workerState: 'stopped',
taskStatus: 'blocked'
})
)
expect(retryHere).not.toThrow()
})
})
describe('#5 placement fence', () => {
it('refuses a local start of a Task being placed on a server, with the ordinary text', () => {
placeTask('task_t')
expect(db.getTask('task_t')?.status).toBe('dispatched')
expect(() =>
db.createStartingWorkerDispatch({
taskId: 'task_t',
startOptions: {},
creator: { kind: 'system' },
maxDepth: Number.MAX_SAFE_INTEGER
})
).toThrow('Task task_t is dispatched; only a ready Task can start.')
})
it('refuses --task naming another Run', () => {
const other = db.createRun({
objective: 'Other',
coordinatorHandle: null,
coordinatorPaneKey: null
})
const foreign = db.createTask({ spec: 'theirs', runId: other.id })
expect(() =>
reserveRemotePlacement(db, {
link,
taskId: foreign.id,
requestKey: 'k'
})
).toThrow(`Task ${foreign.id} was not found in Run ${run.id}.`)
expect(getRemotePlacement(db, foreign.id)).toBeUndefined()
})
it('frees the Task only when the server applied nothing, and a same-key retry finds its reservation', () => {
placeTask('task_t')
expect(placeTask('task_t').placement.state).toBe('reserved')
releaseRemotePlacement(db, 'task_t', 'key_task_t')
expect(getRemotePlacement(db, 'task_t')).toBeUndefined()
expect(db.getTask('task_t')?.status).toBe('ready')
})
it('refuses a start whose deps are unfinished with the ordinary not-ready text', () => {
const dep = db.createTask({ spec: 'first', runId: run.id })
expect(() => placeTask('task_t', 'k', [dep.id])).toThrow(
'Task task_t is pending; only a ready Task can start.'
)
expect(db.getTask('task_t')).toBeUndefined()
})
})
describe('a known older attempt never answers a new reservation', () => {
@@ -290,18 +202,6 @@ describe('remote-owned records on the coordinating Orca', () => {
})
})
describe('a re-made pairing', () => {
it('releases what the old link held, so the Task can be changed here again', () => {
startedOnB('task_t', 'ctx_b1')
openRemoteRunLink(db, run.id, {
...SERVER,
homePeerFingerprint: 'cred_a_new',
pairingRevision: 2
})
expect(db.updateTaskStatus('task_t', 'failed', 'pairing re-made')?.status).toBe('failed')
})
})
describe('#3 late facts after a reset', () => {
for (const reset of ['resetAll', 'resetTasks'] as const) {
it(`records nothing from a start answer that lands after ${reset}`, () => {
@@ -331,32 +231,6 @@ describe('remote-owned records on the coordinating Orca', () => {
expect(getRemotePlacement(db, 'task_t')).toBeUndefined()
})
}
it('records nothing from a start answer that lands after the pairing was re-made', () => {
placeTask('task_t')
openRemoteRunLink(db, run.id, {
...SERVER,
homePeerFingerprint: 'cred_a_new',
pairingRevision: 2
})
expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('closed')
expect(
recordRemoteStart(db, {
conversationId: link.conversation_id,
taskId: 'task_t',
dispatchId: 'ctx_late',
requestKey: 'key_task_t'
})
).toBeUndefined()
expect(getRemoteDispatch(db, 'ctx_late')).toBeUndefined()
})
it('opens a new link for the Run after a reset, so a later start gets its own cancel', () => {
db.resetTasks()
const next = openRemoteRunLink(db, run.id, SERVER)
expect(next.conversation_id).not.toBe(link.conversation_id)
expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('cancel_owed')
})
})
describe('#4 import position', () => {
@@ -392,63 +266,9 @@ describe('remote-owned records on the coordinating Orca', () => {
).toHaveLength(1)
expect(getRemoteRunLink(db, link.conversation_id)?.last_imported_sequence).toBe(3)
})
it('fails each Task when the server reset removed its Dispatch', () => {
startedOnB('task_t', 'ctx_b1')
oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1')
importItem(stateItem('ctx_b1', 'task_t', { removed: 'Reset on devB.' }))
expect(db.getTask('task_t')).toMatchObject({ status: 'failed', result: 'Reset on devB.' })
expect(getRemoteDispatch(db, 'ctx_b1')?.stop_owed).toBe(0)
})
})
describe('#8 settlement through the Task half', () => {
it('completes the Task from the first success and readies its dependents, writing no local execution rows', () => {
startedOnB('task_t', 'ctx_b1')
const dependent = db.createTask({ spec: 'next', runId: run.id, deps: ['task_t'] })
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'completed',
workerState: 'succeeded',
taskStatus: 'completed',
result: 'shipped'
})
)
expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'shipped' })
expect(db.getTask(dependent.id)?.status).toBe('ready')
expect(db.db.prepare('SELECT COUNT(*) AS n FROM dispatch_contexts').get()).toEqual({ n: 0 })
expect(db.db.prepare('SELECT COUNT(*) AS n FROM worker_dispatches').get()).toEqual({ n: 0 })
})
it('lets the first result stand: a later failure and a duplicate success are no-ops', () => {
startedOnB('task_t', 'ctx_b1')
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'completed',
workerState: 'succeeded',
taskStatus: 'completed',
result: 'first'
})
)
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'completed',
workerState: 'succeeded',
taskStatus: 'completed',
result: 'again'
})
)
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'failed',
workerState: 'failed',
taskStatus: 'failed',
result: 'late'
})
)
expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'first' })
})
it('keeps a late D1 failure from failing a Task reopened under D2', () => {
startedOnB('task_t', 'ctx_d1')
importItem(
@@ -491,69 +311,6 @@ describe('remote-owned records on the coordinating Orca', () => {
)
expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'D2' })
})
it("applies the server's unobserved-prompt correction after a failed state item", () => {
startedOnB('task_t', 'ctx_b1')
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'failed',
workerState: 'failed',
taskStatus: 'failed',
result: 'stalled'
})
)
expect(db.getTask('task_t')?.status).toBe('failed')
// Without B's decision, a later success is a second result and does not stand.
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'completed',
workerState: 'succeeded',
taskStatus: 'completed',
result: 'uncorrected'
})
)
expect(db.getTask('task_t')?.status).toBe('failed')
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'completed',
workerState: 'succeeded',
taskStatus: 'completed',
result: 'it worked',
corrected: true
})
)
expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'it worked' })
})
it('ignores a late remote result once the Task was started here', () => {
startedOnB('task_t', 'ctx_d1')
importItem(
stateItem('ctx_d1', 'task_t', {
status: 'failed',
workerState: 'stopped',
taskStatus: 'blocked'
})
)
db.updateTaskStatus('task_t', 'ready')
const local = createRootDispatch(db, 'task_t', 'term_local')
importItem(
stateItem('ctx_d1', 'task_t', {
status: 'failed',
workerState: 'stopped',
taskStatus: 'failed',
result: 'late D1'
})
)
expect(db.getTask('task_t')?.status).toBe('dispatched')
expect(db.getDispatchContextById(local.id)?.status).toBe('dispatched')
})
it('counts a remote attempt as the Task’s active worker for local Task updates', () => {
startedOnB('task_t', 'ctx_b1')
expect(() => db.updateTaskStatus('task_t', 'completed', 'by hand')).toThrow(
'Task task_t cannot move to completed while supervised Dispatch ctx_b1 is active'
)
})
})
describe('a local claim takes the Task back', () => {
@@ -583,141 +340,6 @@ describe('remote-owned records on the coordinating Orca', () => {
)
expect(db.getTask('task_t')).toMatchObject({ status: 'failed', result: 'local D2 failure' })
})
it('lets a local start through once the pairing behind a reservation was re-made', () => {
placeTask('task_t')
openRemoteRunLink(db, run.id, {
...SERVER,
homePeerFingerprint: 'cred_a_new',
pairingRevision: 2
})
db.updateTaskStatus('task_t', 'ready')
const started = db.createStartingWorkerDispatch({
taskId: 'task_t',
startOptions: {},
creator: { kind: 'system' },
maxDepth: Number.MAX_SAFE_INTEGER
})
expect(started.task.status).toBe('dispatched')
expect(getRemotePlacement(db, 'task_t')).toBeUndefined()
})
})
describe('Task guards', () => {
it('refuses a decision gate on a Task a remote worker still holds', () => {
startedOnB('task_t', 'ctx_b1')
expect(() => db.createGate({ taskId: 'task_t', question: 'Ship?' })).toThrow(
'Task task_t cannot open a gate while supervised Dispatch ctx_b1 is active'
)
})
it('keeps holding a Task whose worker finished until its result comes home', () => {
startedOnB('task_t', 'ctx_b1')
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'dispatched',
workerState: 'succeeded',
taskStatus: 'dispatched'
})
)
expect(() => db.updateTaskStatus('task_t', 'completed', 'by hand')).toThrow(
'ctx_b1 is active'
)
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'circuit_broken',
workerState: null,
taskStatus: 'dispatched'
})
)
expect(() => db.updateTaskStatus('task_t', 'failed', 'by hand')).toThrow('ctx_b1 is active')
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'failed',
workerState: null,
taskStatus: 'failed',
result: 'from the server'
})
)
expect(db.getTask('task_t')).toMatchObject({ status: 'failed', result: 'from the server' })
})
it('refuses a local retry of an older local attempt once a server attempt is the latest', () => {
const task = db.createTask({ spec: 'work', runId: run.id })
const d1 = db.createStartingWorkerDispatch({
taskId: task.id,
startOptions: {},
creator: { kind: 'system' },
maxDepth: Number.MAX_SAFE_INTEGER
})
db.failWorkerStart(d1.dispatch.id, 'agent_readiness', 'local failed')
db.updateTaskStatus(task.id, 'ready')
reserveRemotePlacement(db, {
link,
taskId: task.id,
requestKey: 'remote'
})
recordRemoteStart(db, {
conversationId: link.conversation_id,
taskId: task.id,
dispatchId: 'ctx_d2',
requestKey: 'remote'
})
importItem(
stateItem('ctx_d2', task.id, {
status: 'failed',
workerState: 'failed',
taskStatus: 'failed',
result: 'remote failed'
})
)
expect(db.getTask(task.id)?.status).toBe('failed')
expect(() =>
db.createStartingWorkerDispatch({
taskId: task.id,
retryOf: d1.dispatch.id,
startOptions: {},
creator: { kind: 'system' },
maxDepth: Number.MAX_SAFE_INTEGER
})
).toThrow(`Task ${task.id} cannot retry from Dispatch ${d1.dispatch.id}.`)
})
it('refuses to place a Task again on a server whose pairing was re-made since it was placed', () => {
placeTask('task_t', 'k')
openRemoteRunLink(db, run.id, {
...SERVER,
homePeerFingerprint: 'cred_a_new',
pairingRevision: 2
})
db.updateTaskStatus('task_t', 'ready')
expect(() => refuseTaskOfClosedPairing(db, 'task_t', { ...SERVER, name: 'devB' })).toThrow(
'Task task_t was placed through a pairing with devB that was re-made or removed; create a new task to run it there.'
)
expect(db.getTask('task_t')?.status).toBe('ready')
})
it("takes the server's corrected failure text", () => {
startedOnB('task_t', 'ctx_b1')
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'failed',
workerState: 'failed',
taskStatus: 'failed',
result: 'stalled'
})
)
importItem(
stateItem('ctx_b1', 'task_t', {
status: 'failed',
workerState: 'failed',
taskStatus: 'failed',
result: 'real failure',
corrected: true
})
)
expect(db.getTask('task_t')).toMatchObject({ status: 'failed', result: 'real failure' })
})
})
describe('S3 / S8 queue items', () => {
@@ -744,62 +366,5 @@ describe('remote-owned records on the coordinating Orca', () => {
})
expect(db.getTask('task_t')?.status).toBe('completed')
})
it('creates the record of a Dispatch it never heard of from the item, and adopts it as the placement’s attempt', () => {
placeTask('task_t')
importItem(stateItem('ctx_unseen', 'task_t', { status: 'pending', workerState: 'starting' }))
expect(getRemoteDispatch(db, 'ctx_unseen')).toMatchObject({
task_id: 'task_t',
run_id: run.id,
worker_state: 'starting'
})
expect(getRemotePlacement(db, 'task_t')).toMatchObject({
state: 'accepted',
dispatch_id: 'ctx_unseen'
})
})
it('refuses an item whose message ID, Run, peer Run or kind does not match, leaving the position', () => {
startedOnB('task_t', 'ctx_b1')
const good = stateItem('ctx_b1', 'task_t', {})
expect(() => importItem({ ...good, messageId: 'other' })).toThrow('was not imported')
const wrongPeer = JSON.parse(good.payload)
expect(() =>
importItem({
...good,
payload: JSON.stringify({ ...wrongPeer, peerRunId: 'run_elsewhere' })
})
).toThrow('peer Run')
expect(() =>
importItem({ ...good, payload: JSON.stringify({ ...wrongPeer, homeRunId: 'run_other' }) })
).toThrow('belongs to Run')
expect(() => importItem({ ...good, kind: 'worker_future' })).toThrow('kind worker_future')
expect(() => importItem({ ...good, payload: '{"v":2}' })).toThrow('does not match')
expect(getRemoteRunLink(db, link.conversation_id)?.last_imported_sequence).toBe(0)
importItem(good)
expect(getRemoteRunLink(db, link.conversation_id)?.last_imported_sequence).toBe(good.sequence)
})
it('records the question a remote worker asked, and files its mail in the Run mailbox', () => {
startedOnB('task_t', 'ctx_b1')
expect(
importItem(mailItem('msg_q', 'question', { dispatchId: 'ctx_b1', taskId: 'task_t' }))
).toEqual({ to: `run:${run.id}`, type: 'question' })
expect(
db.db
.prepare(
'SELECT dispatch_id, environment_id FROM remote_owned_questions WHERE message_id = ?'
)
.get('msg_q')
).toEqual({ dispatch_id: 'ctx_b1', environment_id: 'env_b' })
expect(db.getUnreadMessages(`run:${run.id}`)).toEqual([
expect.objectContaining({
id: 'msg_q',
type: 'question',
from_handle: 'dispatch:ctx_b1',
body: 'body'
})
])
})
})
})
@@ -14,9 +14,6 @@ import '../../db/dispatch-row-writer'
import '../../db/attempt-outcome-projection'
import { createRootDispatch } from '../../db/root-dispatch-test-fixture'
import { TerminalWorkerTurnStops } from './terminal-worker-turn-stops'
import { reportWorkerTurnStop } from './worker-turn-stop-report'
import type { ChatWorkerPrompt } from '../approvals/chat-worker-approval-prompt'
import type { AgentJournalApprovalItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
const PANE = makePaneKey('tab-worker', '11111111-1111-4111-8111-111111111111')
const HANDLE = 'term_worker'
@@ -92,67 +89,6 @@ function terminal(ctx: ReturnType<typeof setup>, current: { row: AgentStatusIpcP
const settle = () => new Promise((resolve) => setImmediate(resolve))
describe('terminal worker turn stops', () => {
it('tells the Run once, with the last output, when a worker turn ends without worker_done', async () => {
const ctx = setup()
const current = {
row: hookRow({ mainAgent: { state: 'done', outcome: 'failure', stateStartedAt: 200 } })
}
const stops = terminal(ctx, current)
stops.observe(moved('working', 'done'))
await settle()
stops.observe(moved('working', 'done'))
await settle()
const [message, ...rest] = ctx.mail()
expect(rest).toHaveLength(0)
expect(message).toMatchObject({
type: 'escalation',
priority: 'high',
subject: 'Worker stopped on an error without reporting'
})
expect(message.body).toContain('Selected model is at capacity')
expect(message.body).toContain(`worker-read --dispatch ${ctx.dispatch.id}`)
expect(ctx.notify).toHaveBeenCalledWith(message.to_handle, 'escalation')
ctx.db.insertMessage({
from: 'term_coordinator',
to: `dispatch:${ctx.dispatch.id}`,
subject: 'retry',
runId: ctx.run.id
})
// The coordinator's reply starts a new turn; its stop is reported again.
current.row = hookRow({
stateStartedAt: 300,
lastAssistantMessage: 'Read the files. --dispatch-capability dcap_secretsecretsecretsecret00'
})
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail().map((m) => m.subject)).toContain('Worker stopped without reporting')
// A clean finish quotes the agent's own words, not the screen.
expect(ctx.mail()[1].body).toContain('Read the files.')
expect(ctx.mail()[1].body).not.toContain('Selected model')
expect(ctx.mail()[1].body).not.toContain('dcap_secretsecretsecretsecret00')
expect(ctx.mail()).toHaveLength(2)
})
it('waits for a lead and its children to settle before reporting the finish', async () => {
const ctx = setup()
const current = { row: hookRow({ state: 'working', turnCompletedAt: 150 }) }
const stops = terminal(ctx, current)
stops.observe({
kind: 'observed',
paneKey: PANE,
workspace: { worktreeId: 'repo::/tmp/wt', sshHostId: null },
phase: 'working',
at: 1
})
await settle()
expect(ctx.mail()).toHaveLength(0)
current.row = hookRow({ turnCompletedAt: 150 })
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail()).toHaveLength(1)
})
it('drops a stop whose Dispatch was replaced before it was reported', async () => {
const ctx = setup()
const current = { row: hookRow({ state: 'working' }) }
@@ -173,202 +109,6 @@ describe('terminal worker turn stops', () => {
await settle()
expect(ctx.mail()).toHaveLength(0)
})
it('escalates a prompt or error while its helper is open, but not a clean rest', async () => {
const ctx = setup()
const helperTask = ctx.db.createTask({ spec: 'help', runId: ctx.run.id })
ctx.db.createDispatchContext({
taskId: helperTask.id,
assigneeHandle: 'term_helper',
creator: { kind: 'terminal', handle: HANDLE, paneKey: PANE },
maxDepth: Number.MAX_SAFE_INTEGER
})
expect(ctx.db.hasOpenHelperDispatch(ctx.dispatch.id)).toBe(true)
const target = { kind: 'local' as const, dispatch: ctx.dispatch }
const stop = { from: HANDLE, lastOutput: undefined }
reportWorkerTurnStop(ctx.db, target, { ...stop, stopKey: '1', reason: 'finished' }, ctx.deps)
expect(ctx.mail()).toHaveLength(0)
reportWorkerTurnStop(ctx.db, target, { ...stop, stopKey: '2', reason: 'needs-input' }, ctx.deps)
reportWorkerTurnStop(ctx.db, target, { ...stop, stopKey: '3', reason: 'errored' }, ctx.deps)
expect(ctx.mail().map((m) => m.subject)).toEqual([
'Worker is waiting on a prompt',
'Worker stopped on an error without reporting'
])
})
it('stays quiet for a resumed turn, a settled Dispatch, or a deliberate wait', async () => {
const resumed = setup()
const current = { row: hookRow({}) }
const stops = terminal(resumed, current)
stops.observe(moved('working', 'done'))
current.row = hookRow({ state: 'working', stateStartedAt: 250 })
await settle()
expect(resumed.mail()).toHaveLength(0)
const settled = setup()
settled.db.completeDispatch(settled.dispatch.id)
terminal(settled, { row: hookRow({}) }).observe(moved('working', 'done'))
await settle()
expect(settled.mail()).toHaveLength(0)
const waiting = setup()
waiting.waiting.add(`dispatch:${waiting.dispatch.id}`)
terminal(waiting, { row: hookRow({}) }).observe(moved('working', 'done'))
await settle()
expect(waiting.mail()).toHaveLength(0)
})
it('reports an idle finish once until the coordinator writes to the worker again', async () => {
const ctx = setup()
const current = { row: hookRow({}) }
const stops = terminal(ctx, current)
// A worker that wakes on its own schedule ends turn after turn without new mail.
for (const stateStartedAt of [200, 300, 400]) {
current.row = hookRow({ stateStartedAt })
stops.observe(moved('working', 'done'))
await settle()
}
expect(ctx.mail().map((m) => m.subject)).toEqual(['Worker stopped without reporting'])
expect(ctx.mail()[0].body).toContain('later idle turns are not reported until you write to it')
const mail = ctx.db.insertMessage({
from: 'term_coordinator',
to: `dispatch:${ctx.dispatch.id}`,
subject: 'check again',
type: 'status',
runId: ctx.run.id
})
// A helper's reports up to its creator, even a status from a reminted handle, are not the coordinator asking again.
const helperPane = makePaneKey('tab-helper', '33333333-3333-4333-8333-333333333333')
const helper = ctx.db.createDispatchContext({
taskId: ctx.db.createTask({ spec: 'help', runId: ctx.run.id }).id,
assigneeHandle: 'term_helper',
assigneePaneKey: helperPane,
creator: { kind: 'terminal', handle: HANDLE, paneKey: PANE },
maxDepth: Number.MAX_SAFE_INTEGER
})
// Nor are its own heartbeats or a sibling worker's broadcast.
createRootDispatch(
ctx.db,
ctx.db.createTask({ spec: 'sibling', runId: ctx.run.id }).id,
'term_sibling'
)
const helperReports = [
{ from: 'term_helper', type: 'status' as const },
{ from: 'term_helper_reminted', senderPaneKey: helperPane, type: 'status' as const },
{ from: HANDLE, type: 'heartbeat' as const },
{ from: 'term_sibling', type: 'status' as const }
].map((sender) =>
ctx.db.insertMessage({
...sender,
to: `dispatch:${ctx.dispatch.id}`,
subject: 'worker mail',
runId: ctx.run.id
})
)
ctx.db.markAsRead(helperReports.map((report) => report.id))
ctx.db.completeDispatch(helper.id)
// Mail the worker has not taken yet belongs to its next turn, not to a stop seen before it arrived.
current.row = hookRow({ stateStartedAt: 500 })
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail()).toHaveLength(1)
ctx.db.markAsDelivered([mail.id], `dispatch:${ctx.dispatch.id}`)
current.row = hookRow({ stateStartedAt: 600 })
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail()).toHaveLength(1)
ctx.db.markAsRead([mail.id])
current.row = hookRow({ stateStartedAt: 700 })
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail()).toHaveLength(2)
// The coordinator later taking a Dispatch of its own does not turn its earlier guidance into worker mail.
const later = createRootDispatch(
ctx.db,
ctx.db.createTask({ spec: 'later', runId: ctx.run.id }).id,
'term_coordinator'
)
ctx.db.db
.prepare(
"UPDATE dispatch_contexts SET created_at = datetime('now', '+1 minute') WHERE id = ?"
)
.run(later.id)
const next = ctx.db.insertMessage({
from: 'term_run_owner',
to: `dispatch:${ctx.dispatch.id}`,
subject: 'one more',
runId: ctx.run.id
})
ctx.db.markAsRead([next.id])
current.row = hookRow({ stateStartedAt: 800 })
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail()).toHaveLength(3)
})
it('stays quiet after the worker asks and ends its turn, until the answer arrives', async () => {
const ctx = setup()
const question = ctx.db.createQuestion({
runId: ctx.run.id,
dispatchId: ctx.dispatch.id,
askerHandle: HANDLE,
question: 'Which file?'
})
const current = { row: hookRow({}) }
const stops = terminal(ctx, current)
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail()).toHaveLength(0)
ctx.db.answerQuestion({
messageId: question.message.id,
runId: ctx.run.id,
consumerGeneration: ctx.run.consumer_generation,
body: 'main.ts'
})
current.row = hookRow({ stateStartedAt: 300 })
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail().map((m) => m.subject)).toEqual(['Worker stopped without reporting'])
})
it('reports a later stall once new mail reached the worker, though its question is pending', async () => {
const ctx = setup()
// Mail stored before the question, even in the same second, does not end the asking turn's mute.
ctx.db.insertMessage({
from: 'term_coordinator',
to: `dispatch:${ctx.dispatch.id}`,
subject: 'Steer',
runId: ctx.run.id
})
const question = ctx.db.createQuestion({
runId: ctx.run.id,
dispatchId: ctx.dispatch.id,
askerHandle: HANDLE,
question: 'Which file?'
})
const current = { row: hookRow({}) }
const stops = terminal(ctx, current)
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.mail()).toHaveLength(0)
ctx.db.insertMessage({
from: 'term_coordinator',
to: `dispatch:${ctx.dispatch.id}`,
subject: 'Change of plan',
runId: ctx.run.id
})
current.row = hookRow({ stateStartedAt: 300 })
stops.observe(moved('working', 'done'))
await settle()
expect(ctx.db.getQuestion(question.message.id)?.status).toBe('pending')
expect(ctx.mail().map((m) => m.subject)).toEqual(['Worker stopped without reporting'])
})
})
describe('chat worker turn stops', () => {
@@ -415,14 +155,11 @@ describe('chat worker turn stops', () => {
function chatWithTimers(ctx: ReturnType<typeof setup>) {
const timers: (() => void)[] = []
let status: 'idle' | 'working' = 'idle'
const status = 'idle' as const
const report = chatWorkerTurnStopReporter(ctx.deps, (run) => timers.push(run))
return {
finish: (turnId: string) =>
report(completion('success', turnId), () => ({ status, lastAssistantMessage: 'Done.' })),
setStatus: (next: typeof status) => {
status = next
},
runTimers: () => {
for (const run of timers.splice(0)) {
run()
@@ -431,37 +168,6 @@ describe('chat worker turn stops', () => {
}
}
it('does not blame a follow-up for the turn whose report claimed it', () => {
const ctx = setup()
const followUp = startingFollowUp(ctx)
const chat = chatWithTimers(ctx)
chat.finish('turn-reported')
chat.runTimers()
ctx.db.markWorkerDispatchReady(followUp)
chat.setStatus('working')
chat.runTimers()
expect(ctx.mail()).toHaveLength(0)
})
it('drops a pending stop once a later turn of the follow-up fails', () => {
const ctx = setup()
const followUp = startingFollowUp(ctx)
ctx.db.markWorkerDispatchReady(followUp)
const timers: (() => void)[] = []
const report = chatWorkerTurnStopReporter(ctx.deps, (run) => timers.push(run))
const idle = () => ({ status: 'idle' as const, lastAssistantMessage: 'It failed.' })
report(completion('success', 'turn-reported'), idle)
report(completion('failure', 'turn-follow-up'), idle)
for (const run of timers.splice(0)) {
run()
}
expect(ctx.mail()).toHaveLength(0)
})
it('still reports a follow-up whose own turn ended before its start settled', () => {
const ctx = setup()
const followUp = startingFollowUp(ctx)
@@ -478,309 +184,3 @@ describe('chat worker turn stops', () => {
])
})
})
describe('remote worker turn stops', () => {
it('relays the report to the Run home under a stable id', () => {
const db = new OrchestrationDb(':memory:')
const enqueueFederationRelay = vi.spyOn(db, 'enqueueFederationRelay')
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const attachment = { dispatch_id: 'dsp_remote', task_id: 'task_remote' }
const stop = { from: HANDLE, stopKey: 'k', reason: 'finished' as const, lastOutput: 'bye' }
const deps = { getDb: () => db, isWaitingForMail: () => false, notify: vi.fn() }
const target = { kind: 'remote' as const, attachment }
reportWorkerTurnStop(db, target, stop, deps)
reportWorkerTurnStop(db, target, stop, deps)
const [first, second] = enqueueFederationRelay.mock.calls.map(([params]) => params)
expect(first).toMatchObject({
dispatchId: 'dsp_remote',
direction: 'to_home',
kind: 'escalation'
})
expect(first.messageId).toBe(second.messageId)
// The repeat is a no-op, not a failed relay.
expect(warn).not.toHaveBeenCalled()
const relayed = JSON.parse(first.payload)
expect(relayed).toMatchObject({ type: 'escalation', priority: 'high' })
expect(JSON.parse(relayed.payload)).toMatchObject({ stopReason: 'finished' })
// A worker_done still queued for the home is a report, not a silent stop.
db.enqueueFederationRelay({
dispatchId: 'dsp_remote',
direction: 'to_home',
kind: 'worker_done',
payload: '{}'
})
enqueueFederationRelay.mockClear()
reportWorkerTurnStop(db, target, { ...stop, stopKey: 'k2' }, deps)
expect(enqueueFederationRelay).not.toHaveBeenCalled()
})
})
describe('chat worker approvals', () => {
const promptEvent = (promptId: string): AgentSessionTurnCompletionEvent => ({
type: 'prompt',
prompt: {
scope: {
executionHostId: LOCAL_EXECUTION_HOST_ID,
wslDistro: null,
workspaceId: 'repo::/tmp/wt',
workspaceKind: 'git-worktree'
},
sessionId: CHAT_SESSION,
promptId,
raisedAt: 1
}
})
const approval = (selected: string | null): AgentJournalApprovalItem => ({
kind: 'approval',
title: 'Allow Bash?',
detail: 'rm -rf build',
options: [
{ id: 'allow', label: 'Allow', intent: 'allow_once' },
{ id: 'deny', label: 'Deny', intent: 'reject_once' }
],
resolution: selected
? {
state: 'resolved',
selectedOptionId: selected,
resolvedBy: 'desktop-renderer',
resolvedAt: 2
}
: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null }
})
function chat() {
const ctx = setup(formatOrcaSessionAddress(CHAT_SESSION))
const prompts = new Map<string, ChatWorkerPrompt>()
const unreadable = { now: false }
// The worker's journal publishing a change, as when its own chat answers a prompt.
const journalChanged = new Map<string, () => void>()
const report = chatWorkerTurnStopReporter(
ctx.deps,
(run) => run(),
async (_sessionId, itemId) => {
if (unreadable.now) {
throw new Error('journal unreadable')
}
return prompts.get(itemId) ?? null
},
(sessionId, onChange) => {
journalChanged.set(sessionId, onChange)
return () => journalChanged.delete(sessionId)
}
)
const publish = () => journalChanged.get(CHAT_SESSION)?.()
const idle = () => ({ status: 'idle' as const, lastAssistantMessage: '' })
const all = () => ctx.db.getUnreadRunMailbox(ctx.run.id, 100)
return { ctx, prompts, unreadable, report, publish, idle, all }
}
it('escalates one open approval once, with its structured payload', async () => {
const { ctx, prompts, report, idle } = chat()
prompts.set('item_1', { revision: 1, body: approval(null) })
report(promptEvent('item_1'), idle)
report(promptEvent('item_1'), idle)
await settle()
const mail = ctx.mail()
expect(mail).toHaveLength(1)
expect(mail[0].subject).toBe('Worker is waiting for permission')
expect(mail[0].body).toContain(
`orchestration deny --dispatch ${ctx.dispatch.id} --prompt item_1`
)
expect(mail[0].body).not.toContain('Answer it with')
expect(JSON.parse(mail[0].payload ?? '{}').approval).toEqual({
v: 1,
approvalId: 'item_1',
state: 'open',
worker: {
handle: formatOrcaSessionAddress(CHAT_SESSION),
dispatchId: ctx.dispatch.id,
taskId: ctx.dispatch.task_id
},
summary: { title: 'Allow Bash?', detail: 'rm -rf build', reason: null },
allowedActions: ['allow', 'deny']
})
})
it("words an approval for the coordinator's surface, and offers deny only when the prompt has one", () => {
const report = (chatCoordinator: boolean | undefined, actions: ('allow' | 'deny')[]) => {
const ctx = setup()
reportWorkerTurnStop(
ctx.db,
{ kind: 'local', dispatch: ctx.dispatch },
{
from: HANDLE,
stopKey: 's1',
reason: 'needs-input',
lastOutput: undefined,
approval: {
v: 1,
approvalId: 'apr_1',
state: 'open',
worker: { handle: HANDLE, dispatchId: ctx.dispatch.id, taskId: ctx.dispatch.task_id },
summary: { title: 'Allow Bash?', detail: 'rm -rf build', reason: null },
allowedActions: actions
}
},
chatCoordinator === undefined
? ctx.deps
: { ...ctx.deps, isChatMailbox: () => chatCoordinator }
)
return { body: ctx.mail()[0].body, dispatchId: ctx.dispatch.id }
}
const chat = report(true, ['allow', 'deny'])
expect(chat.body).toContain('The user has been shown Allow/Deny in your chat in Orca.')
expect(chat.body).toContain(`orchestration deny --dispatch ${chat.dispatchId} --prompt apr_1`)
for (const terminal of [report(false, ['allow', 'deny']), report(undefined, ['allow'])]) {
expect(terminal.body).toContain(
`No one has been shown this prompt in Orca. Tell the user that worker ${HANDLE} is waiting for permission in its terminal.`
)
expect(terminal.body).not.toContain('The user has been shown')
}
const chatWorker = setup(formatOrcaSessionAddress(CHAT_SESSION))
reportWorkerTurnStop(
chatWorker.db,
{ kind: 'local', dispatch: chatWorker.dispatch },
{
from: formatOrcaSessionAddress(CHAT_SESSION),
stopKey: 's1',
reason: 'needs-input',
lastOutput: undefined,
approval: {
v: 1,
approvalId: 'item_1',
state: 'open',
worker: {
handle: formatOrcaSessionAddress(CHAT_SESSION),
dispatchId: chatWorker.dispatch.id,
taskId: chatWorker.dispatch.task_id
},
summary: { title: 'Allow Bash?', detail: null, reason: null },
allowedActions: ['allow', 'deny']
}
},
chatWorker.deps
)
// A chat worker's own chat in Orca shows the prompt, even when the coordinator has no card.
expect(chatWorker.mail()[0].body).toContain(
"Your chat has no approval card for it; only the worker's own chat in Orca shows it."
)
const noDeny = report(true, ['allow']).body
expect(noDeny).toContain('The user has been shown Allow in your chat in Orca.')
expect(noDeny).not.toContain('orchestration deny')
expect(noDeny).toContain('stop the worker or tell the user')
})
it('closes a reported approval once, as soon as the worker chat answers it', async () => {
const { prompts, report, publish, idle, all } = chat()
prompts.set('item_1', { revision: 1, body: approval(null) })
report(promptEvent('item_1'), idle)
await settle()
// No turn edge: the journal change alone closes it.
prompts.set('item_1', { revision: 2, body: approval('deny') })
publish()
publish()
await settle()
const closing = all().filter((message) => message.type === 'status')
expect(closing).toHaveLength(1)
expect(closing[0].body).toContain("Denied in the worker's own chat")
expect(JSON.parse(closing[0].payload ?? '{}').approval).toMatchObject({
approvalId: 'item_1',
state: 'answered',
allowedActions: [],
outcome: { by: 'worker-chat', decision: 'deny' }
})
})
it('keeps watching a reported approval through an unreadable chat', async () => {
const { prompts, unreadable, report, publish, idle, all } = chat()
prompts.set('item_1', { revision: 1, body: approval(null) })
report(promptEvent('item_1'), idle)
await settle()
prompts.set('item_1', { revision: 2, body: approval('deny') })
unreadable.now = true
publish()
await settle()
expect(all().filter((message) => message.type === 'status')).toHaveLength(0)
unreadable.now = false
publish()
await settle()
const closing = all().filter((message) => message.type === 'status')
expect(closing).toHaveLength(1)
expect(closing[0].body).toContain("Denied in the worker's own chat")
})
it('keeps a settled approval until its closing line can be written', async () => {
const { ctx, prompts, report, publish, idle, all } = chat()
prompts.set('item_1', { revision: 1, body: approval(null) })
report(promptEvent('item_1'), idle)
await settle()
prompts.set('item_1', { revision: 2, body: approval('deny') })
const getDb = ctx.deps.getDb
ctx.deps.getDb = () => null
publish()
await settle()
ctx.deps.getDb = getDb
publish()
await settle()
const closing = all().filter((message) => message.subject === 'Worker approval answered')
expect(closing).toHaveLength(1)
})
it('reports a prompt Orca can answer neither way as a plain prompt, with no card', async () => {
const { ctx, prompts, report, idle } = chat()
prompts.set('item_1', {
revision: 1,
body: {
...approval(null),
options: [{ id: 'always', label: 'Always allow', intent: 'allow_always' }]
}
})
report(promptEvent('item_1'), idle)
await settle()
const [mail] = ctx.mail()
expect(mail.subject).toBe('Worker is waiting on a prompt')
expect(JSON.parse(mail.payload ?? '{}').approval).toBeUndefined()
})
it('closes an approval left open by an earlier run once its worker is gone', async () => {
const { ctx, prompts, report, idle, all } = chat()
prompts.set('item_1', { revision: 1, body: approval(null) })
report(promptEvent('item_1'), idle)
await settle()
ctx.db.db
.prepare(`UPDATE dispatch_contexts SET status = 'completed' WHERE id = ?`)
.run(ctx.dispatch.id)
// A restart builds a new reporter; it picks up approvals whose closing line never came.
chatWorkerTurnStopReporter(ctx.deps, (run) => run())
chatWorkerTurnStopReporter(ctx.deps, (run) => run())
await settle()
const closing = all().filter((message) => message.subject === 'Worker approval closed')
expect(closing).toHaveLength(1)
expect(closing[0].body).toContain('Closed without an answer Orca can name: approval item_1')
})
it('tells the coordinator a plain prompt needs a person, not a message', async () => {
const { ctx, report, idle } = chat()
report(promptEvent('question_1'), idle)
await settle()
const [mail] = ctx.mail()
expect(mail.subject).toBe('Worker is waiting on a prompt')
expect(mail.body).toContain('A message does not answer it')
expect(mail.body).not.toContain('Answer it with')
})
})
@@ -1,12 +1,4 @@
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
truncateSync,
unlinkSync,
writeFileSync
} from 'node:fs'
import { mkdtempSync, rmSync, truncateSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -14,11 +6,7 @@ import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
MOBILE_WEB_BUNDLE_CHUNK_BYTES,
MobileWebBundleChunkResultSchema,
MobileWebBundleManifestResultSchema
} from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract'
import { MobileWebBundleManifestResultSchema } from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract'
import '../../server/runtime-rpc-mobile-method-allowlist'
import type { RpcRequest, RpcResponse } from '../../core'
@@ -37,7 +25,6 @@ import {
installMobileWebBundleAppPath,
mobileWebBundleDispatcher,
mobileWebBundleFiller,
sha256Hex,
writeSyntheticMobileWebBundle,
type SyntheticMobileWebBundle
} from './mobile-web-bundle.test-fixture'
@@ -63,31 +50,6 @@ async function chunk(params: unknown, options?: DispatchOptions) {
return call('mobileWeb.bundle.chunk', params, options)
}
/** Pages one asset to the end the way a client must: never assuming a size it did not read. */
async function download(buildId: string, path: string): Promise<{ bytes: Buffer; calls: number }> {
const pieces: Buffer[] = []
let offset = 0
let calls = 0
for (;;) {
const response = await chunk({ buildId, path, offset })
calls++
if (!response.ok) {
throw new Error(`chunk at ${String(offset)} failed: ${response.error.message}`)
}
const body = MobileWebBundleChunkResultSchema.parse(response.result)
expect(body.buildId).toBe(buildId)
expect(body.path).toBe(path)
expect(body.offset).toBe(offset)
pieces.push(Buffer.from(body.dataBase64, 'base64'))
if (body.eof) {
expect(offset + pieces.at(-1)!.byteLength).toBe(body.assetByteLength)
break
}
offset += MOBILE_WEB_BUNDLE_CHUNK_BYTES
}
return { bytes: Buffer.concat(pieces), calls }
}
beforeEach(() => {
scratch = mkdtempSync(join(tmpdir(), 'orca-mobile-web-bundle-'))
installMobileWebBundleAppPath(scratch)
@@ -109,42 +71,6 @@ describe('an install that carries a mobile web bundle', () => {
bundle = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 1)
})
it('pages every asset back byte for byte, and each reassembly matches its manifest hash', async () => {
for (const asset of bundle.assets) {
const { bytes, calls } = await download(bundle.buildId, asset.path)
expect(bytes.byteLength).toBe(asset.byteLength)
expect(sha256Hex(bytes)).toBe(asset.sha256)
expect(calls).toBe(Math.max(1, Math.ceil(asset.byteLength / MOBILE_WEB_BUNDLE_CHUNK_BYTES)))
}
})
// Exact chunk multiples must report EOF now; the next offset is invalid.
it('ends an exactly-one-chunk asset on its first chunk', async () => {
const stylesheet = bundle.assets.find((asset) => asset.path.endsWith('.css'))!
expect(stylesheet.byteLength).toBe(MOBILE_WEB_BUNDLE_CHUNK_BYTES)
const first = await chunk({ buildId: bundle.buildId, path: stylesheet.path, offset: 0 })
const past = await chunk({
buildId: bundle.buildId,
path: stylesheet.path,
offset: MOBILE_WEB_BUNDLE_CHUNK_BYTES
})
expect(MobileWebBundleChunkResultSchema.parse(first.ok && first.result).eof).toBe(true)
expect(errorMessage(past)).toBe('mobile_web_bundle_offset_invalid')
})
// Allow offset zero for empty assets so clients can fetch every manifest member.
it('serves a zero-byte asset as one empty chunk at eof', async () => {
const mark = bundle.assets.find((asset) => asset.byteLength === 0)!
const response = await chunk({ buildId: bundle.buildId, path: mark.path, offset: 0 })
const body = MobileWebBundleChunkResultSchema.parse(response.ok && response.result)
expect(body).toMatchObject({ dataBase64: '', eof: true, assetByteLength: 0 })
})
// Linux package managers replace the install under a running host (STA-14385): serve the new build, never the gone one.
it('serves the replacement build after the install swaps bundles under a running host', async () => {
const script = bundle.assets.find((asset) => asset.path.endsWith('.js'))!
@@ -166,69 +92,6 @@ describe('an install that carries a mobile web bundle', () => {
expect(errorMessage(fresh)).toBeUndefined()
})
// A newer release written in place may add schema-v1 fields this host predates; it serves only the ones it knows.
it('serves a replacement manifest that carries fields this host does not know', async () => {
rmSync(join(scratch, 'out', 'mobile-web'), { recursive: true, force: true })
const replacement = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 5)
const manifestPath = join(replacement.root, 'manifest.json')
const written = JSON.parse(readFileSync(manifestPath, 'utf8'))
written.assets[0].laterAssetField = 1
written.laterManifestField = true
writeFileSync(manifestPath, JSON.stringify(written), 'utf8')
const response = await call('mobileWeb.bundle.manifest')
const manifest = MobileWebBundleManifestResultSchema.parse(
response.ok && response.result
).manifest
expect(manifest.buildId).toBe(replacement.buildId)
})
// A path survives rebuild; key verdicts by build too so an old failure cannot poison new bytes.
it('does not carry a failed verdict from one build onto the next build of the same path', async () => {
writeFileSync(join(bundle.root, 'index.html'), mobileWebBundleFiller(640, 99))
expect(
errorMessage(await chunk({ buildId: bundle.buildId, path: 'index.html', offset: 0 }))
).toBe('mobile_web_bundle_asset_changed')
rmSync(join(scratch, 'out', 'mobile-web'), { recursive: true, force: true })
const replacement = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 8)
const response = await chunk({ buildId: replacement.buildId, path: 'index.html', offset: 0 })
expect(errorMessage(response)).toBeUndefined()
})
// A package install writes the manifest and assets one file at a time; a mismatch mid-install must not stick.
it('serves an asset once its bytes match again, after a mismatch for the same build', async () => {
const original = mobileWebBundleFiller(640, 3)
writeFileSync(join(bundle.root, 'index.html'), mobileWebBundleFiller(640, 99))
expect(
errorMessage(await chunk({ buildId: bundle.buildId, path: 'index.html', offset: 0 }))
).toBe('mobile_web_bundle_asset_changed')
writeFileSync(join(bundle.root, 'index.html'), original)
const response = await chunk({ buildId: bundle.buildId, path: 'index.html', offset: 0 })
expect(errorMessage(response)).toBeUndefined()
})
// Map post-verification filesystem failure to a contract code without exposing the host install path.
it('answers a changed asset, not the filesystem error, when the asset is gone after its verdict', async () => {
const script = bundle.assets.find((asset) => asset.path.endsWith('.js'))!
expect((await chunk({ buildId: bundle.buildId, path: script.path, offset: 0 })).ok).toBe(true)
unlinkSync(join(bundle.root, script.path))
const response = await chunk({
buildId: bundle.buildId,
path: script.path,
offset: MOBILE_WEB_BUNDLE_CHUNK_BYTES
})
expect(errorMessage(response)).toBe('mobile_web_bundle_asset_changed')
expect(console.warn).toHaveBeenCalled()
})
// Truncation after verification must not return a short chunk and let clients page past missing bytes.
it('answers a changed asset when the file is shorter than the manifest promised', async () => {
const script = bundle.assets.find((asset) => asset.path.endsWith('.js'))!
@@ -239,109 +102,6 @@ describe('an install that carries a mobile web bundle', () => {
expect(errorMessage(response)).toBe('mobile_web_bundle_asset_changed')
})
it('stops before reading anything for a client that already disconnected', async () => {
const controller = new AbortController()
controller.abort()
const response = await chunk(
{ buildId: bundle.buildId, path: 'index.html', offset: 0 },
{
signal: controller.signal
}
)
expect(response.ok).toBe(false)
expect(errorMessage(response)).toBe('client_disconnected')
})
})
describe('the language catalogs a build serves on request', () => {
let bundle: SyntheticMobileWebBundle
beforeEach(() => {
bundle = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 1, [], {
de: { greeting: 'Hallo' }
})
})
it('serves the listed catalog, then nothing to a phone that already holds it', async () => {
const [german] = bundle.catalogs
const first = await call('mobileWeb.bundle.localeCatalog', { locale: 'de' })
const again = await call('mobileWeb.bundle.localeCatalog', {
locale: 'de',
knownSha256: german.sha256
})
expect(first.ok && first.result).toEqual({
locale: 'de',
sha256: german.sha256,
catalog: { greeting: 'Hallo' }
})
expect(again.ok && again.result).toEqual({
locale: 'de',
sha256: german.sha256,
catalog: null
})
})
it('refuses a locale the build has no catalog for, and a catalog file that changed', async () => {
writeFileSync(join(bundle.root, bundle.catalogs[0].path), '{"greeting":"Servus"}')
const french = await call('mobileWeb.bundle.localeCatalog', { locale: 'fr' })
const changed = await call('mobileWeb.bundle.localeCatalog', { locale: 'de' })
expect(errorMessage(french)).toBe('mobile_web_bundle_asset_unknown')
expect(errorMessage(changed)).toBe('mobile_web_bundle_asset_changed')
})
})
describe('where the resolver probes', () => {
it('finds the bundle beside an out/main app path', async () => {
const bundle = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 3)
installMobileWebBundleAppPath(join(scratch, 'out', 'main'))
const response = await call('mobileWeb.bundle.manifest')
expect(
MobileWebBundleManifestResultSchema.parse(response.ok && response.result).manifest.buildId
).toBe(bundle.buildId)
})
it('reads a packaged app from app.asar.unpacked, where an in-place update writes its files', async () => {
const bundle = writeSyntheticMobileWebBundle(
join(scratch, 'app.asar.unpacked', 'out', 'mobile-web'),
4
)
installMobileWebBundleAppPath(join(scratch, 'app.asar'))
const response = await call('mobileWeb.bundle.manifest')
expect(
MobileWebBundleManifestResultSchema.parse(response.ok && response.result).manifest.buildId
).toBe(bundle.buildId)
})
})
describe('an install with no mobile web bundle', () => {
it('reports both methods unavailable rather than failing some other way', async () => {
const manifest = await call('mobileWeb.bundle.manifest')
const body = await chunk({ buildId: '0'.repeat(64), path: 'index.html', offset: 0 })
expect(errorMessage(manifest)).toBe('mobile_web_bundle_unavailable')
expect(errorMessage(body)).toBe('mobile_web_bundle_unavailable')
})
it('reads an unparseable manifest as no bundle at all', async () => {
const root = join(scratch, 'out', 'mobile-web')
mkdirSync(root, { recursive: true })
writeFileSync(join(root, 'manifest.json'), 'not json', 'utf8')
expect(errorMessage(await call('mobileWeb.bundle.manifest'))).toBe(
'mobile_web_bundle_unavailable'
)
})
})
// Regular-file reads may split before EOF; fill the window before returning a chunk.
@@ -371,12 +131,4 @@ describe('filling a read window', () => {
expect(stub.calls).toEqual([64, 40])
expect(buffer.equals(source)).toBe(true)
})
it('stops at the read that returns nothing, which is the truncation the caller reports', async () => {
const stub = reader([24, 0])
const filled = await fillMobileWebBundleReadWindow(stub, Buffer.alloc(64), 64, 0)
expect(filled).toBe(24)
})
})
@@ -1,414 +0,0 @@
// @vitest-environment happy-dom
// Exercise the real desktop writer/UI slice and persistence merge with queued IPC broadcasts; model Expo mobile mapping locally. Disjoint edits must survive stale mirrors and converge (STA-5781).
import { StrictMode, act, createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { StoreApi } from 'zustand/vanilla'
import { getDefaultUIState } from '../../../shared/constants'
import type { PersistedUIState } from '../../../shared/persisted-ui-state-types'
import type { PersistedState } from '../../../shared/persisted-state-types'
import { getPersistedUI } from '../../../main/persistence/applying-settings/ui-state-read'
import {
updatePersistedUI,
type UIUpdateOperations
} from '../../../main/persistence/applying-settings/ui-state-update'
import type { AppState } from '../store/types'
import { createUIStore } from '../store/slices/ui/ui-slice-test-harness'
import {
capturePersistedUIWriteBaseline,
diffPersistedUIWriteFields
} from '../store/slices/ui/persisted-ui-write-baseline'
import { usePersistedUIWriter } from './use-persisted-ui-writer'
const storeRef = vi.hoisted(() => ({
current: null as unknown as StoreApi<unknown>
}))
vi.mock('../store', async () => {
const { useStore } = await import('zustand')
const useAppStore = (selector: (s: unknown) => unknown) => useStore(storeRef.current, selector)
useAppStore.getState = () => storeRef.current.getState()
useAppStore.setState = (partial: never) => storeRef.current.setState(partial)
useAppStore.subscribe = (listener: never) => storeRef.current.subscribe(listener)
return { useAppStore }
})
/** The main-process authority: the real ui.set merge over a real PersistedState. */
function createAuthority() {
const state = { ui: { ...getDefaultUIState() } } as PersistedState
let activeView: PersistedState['ui']['activeView'] = 'terminal'
const listeners = new Set<(ui: PersistedUIState) => void>()
const operations: UIUpdateOperations = {
state,
removeRetainedBlob: () => {},
setActiveView: (next) => {
if (next === undefined || next === activeView) {
return false
}
activeView = next
return true
},
getUI: () => getPersistedUI(state, activeView),
scheduleSave: () => {},
notifyUIChanged: () => {
const ui = getPersistedUI(state, activeView)
for (const listener of listeners) {
listener(ui)
}
}
}
return {
set: (updates: Partial<PersistedUIState>) => updatePersistedUI(operations, updates),
get: () => getPersistedUI(state, activeView),
onChanged: (listener: (ui: PersistedUIState) => void) => listeners.add(listener)
}
}
type Authority = ReturnType<typeof createAuthority>
describe('workspace view preferences: cross-client persistence (STA-5781)', () => {
let authority: Authority
let store: StoreApi<AppState>
let root: Root
let container: HTMLDivElement
let pendingBroadcasts: PersistedUIState[]
let holdAcks: boolean
let rejectSets: boolean
let rejectNextSet: boolean
let setCallCount: number
let pendingAcks: (() => void)[]
let pendingRejects: ((reason?: unknown) => void)[]
async function resolveAcks() {
await act(async () => {
for (const resolve of pendingAcks.splice(0)) {
resolve()
}
await Promise.resolve()
})
}
function deliverBroadcasts() {
const queued = pendingBroadcasts.splice(0)
for (const ui of queued) {
act(() => {
store.getState().hydratePersistedUI(ui, 'sync')
})
}
}
function mountDesktopWriter() {
function Probe() {
usePersistedUIWriter()
return null
}
// Match real StrictMode mount/cleanup replay.
act(() => {
root.render(createElement(StrictMode, null, createElement(Probe)))
})
}
async function flushDesktopDebounce() {
// Drain the ack microtask so the writer folds its baseline before assertions.
await act(async () => {
vi.advanceTimersByTime(200)
await Promise.resolve()
})
}
beforeEach(() => {
vi.useFakeTimers()
authority = createAuthority()
pendingBroadcasts = []
authority.onChanged((ui) => pendingBroadcasts.push(ui))
store = createUIStore()
storeRef.current = store as unknown as typeof storeRef.current
holdAcks = false
rejectSets = false
rejectNextSet = false
setCallCount = 0
pendingAcks = []
pendingRejects = []
;(window as unknown as { api: unknown }).api = {
ui: {
set: (updates: Partial<PersistedUIState>) => {
setCallCount += 1
// rejectSets models transport failure: nothing reaches the host.
if (rejectSets) {
return Promise.reject(new Error('transport failure'))
}
if (rejectNextSet) {
rejectNextSet = false
return new Promise<void>((_, reject) => pendingRejects.push(reject))
}
// Apply before resolving as IPC does; held acks expose the in-flight window.
authority.set(updates)
if (!holdAcks) {
return Promise.resolve()
}
return new Promise<void>((resolve) => pendingAcks.push(resolve))
}
}
}
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
act(() => {
store.getState().hydratePersistedUI(authority.get(), 'startup')
})
mountDesktopWriter()
})
afterEach(() => {
act(() => {
root.unmount()
})
container.remove()
vi.useRealTimers()
})
it('saves a revealed remote host after an unrelated older broadcast', async () => {
act(() => {
authority.set({ workspaceHostScope: 'local', visibleWorkspaceHostIds: ['local'] })
})
deliverBroadcasts()
act(() => {
authority.set({ sidebarWidth: 320 })
store.getState().setVisibleWorkspaceHostIds(['local', 'runtime:m4air'])
})
pendingBroadcasts.reverse()
deliverBroadcasts()
expect(store.getState().visibleWorkspaceHostIds).toEqual(['local', 'runtime:m4air'])
await flushDesktopDebounce()
deliverBroadcasts()
expect(authority.get().visibleWorkspaceHostIds).toEqual(['local', 'runtime:m4air'])
expect(authority.get().sidebarWidth).toBe(320)
})
it('saves a changed activity bar position', async () => {
act(() => store.setState({ activityBarPosition: 'side' }))
await flushDesktopDebounce()
expect(authority.get().activityBarPosition).toBe('side')
})
it('saves All hosts after flipping back during a host-selection write', async () => {
holdAcks = true
act(() => store.getState().setWorkspaceHostScope('local'))
await flushDesktopDebounce()
act(() => store.getState().setWorkspaceHostScope('all'))
deliverBroadcasts()
expect(store.getState().visibleWorkspaceHostIds).toBeNull()
expect(store.getState().workspaceHostScope).toBe('all')
await resolveAcks()
holdAcks = false
await flushDesktopDebounce()
deliverBroadcasts()
expect(authority.get().visibleWorkspaceHostIds).toBeNull()
expect(authority.get().workspaceHostScope).toBe('all')
})
it('the desktop debounced writer preserves a concurrent client’s field', async () => {
// t=0: desktop toggles a desktop-only filter (disjoint from mobile fields).
act(() => {
store.getState().setHideCliCreatedWorkspaces(true)
})
// Apply mobile’s disjoint edit before the desktop debounce, but delay its broadcast.
act(() => {
vi.advanceTimersByTime(100)
})
authority.set({ hideSleepingWorkspaces: true })
expect(authority.get().hideSleepingWorkspaces).toBe(true)
// Flush the desktop’s still-stale mirror.
await flushDesktopDebounce()
expect(authority.get().hideCliCreatedWorkspaces).toBe(true)
expect(authority.get().hideSleepingWorkspaces).toBe(true)
deliverBroadcasts()
expect(store.getState().showSleepingWorkspaces).toBe(false)
expect(store.getState().hideCliCreatedWorkspaces).toBe(true)
})
it('a broadcast landing inside the debounce window must not revert the pending desktop toggle', async () => {
// t=0: desktop toggles a filter; its write is pending in the 150ms debounce.
act(() => {
store.getState().setHideCliCreatedWorkspaces(true)
})
// t<150ms: another client changes a disjoint field AND its broadcast is delivered
// before the desktop debounce fires. The broadcast still carries the OLD
// value of the desktop's pending toggle.
authority.set({ hideSleepingWorkspaces: true })
deliverBroadcasts()
expect(store.getState().hideCliCreatedWorkspaces).toBe(true)
expect(store.getState().showSleepingWorkspaces).toBe(false)
await flushDesktopDebounce()
expect(authority.get().hideCliCreatedWorkspaces).toBe(true)
expect(authority.get().hideSleepingWorkspaces).toBe(true)
})
it('preserves a flip-back made while the first write is still in flight', async () => {
// A flip-back matches the pre-ack baseline. Track in-flight fields so an obsolete ack/echo cannot erase the second toggle (PR #17057).
holdAcks = true
act(() => {
store.getState().setHideDefaultBranchWorkspace(true)
})
await flushDesktopDebounce()
expect(authority.get().hideDefaultBranchWorkspace).toBe(true)
act(() => {
store.getState().setHideDefaultBranchWorkspace(false)
})
// Deliver the first write’s echo before its ack.
deliverBroadcasts()
expect(store.getState().hideDefaultBranchWorkspace).toBe(false)
await resolveAcks()
await flushDesktopDebounce()
await resolveAcks()
expect(authority.get().hideDefaultBranchWorkspace).toBe(false)
deliverBroadcasts()
expect(store.getState().hideDefaultBranchWorkspace).toBe(false)
})
it('a terminal rejection leaves one dirty field without an automatic retry loop', async () => {
// Keep rejection dirty for a later edit without scheduling an endless trailing retry loop.
rejectSets = true
setCallCount = 0
act(() => {
store.getState().setHideDefaultBranchWorkspace(true)
})
vi.advanceTimersByTime(150)
// Settle rejection without firing any erroneously rearmed timer yet.
await Promise.resolve()
// Assert transport count, settled markers and no retry timer independently; the field stays dirty.
expect(setCallCount).toBe(1)
expect(store.getState().persistedUIWriteInFlightCounts).toEqual({})
const state = store.getState()
expect(
diffPersistedUIWriteFields(
capturePersistedUIWriteBaseline(state),
state.persistedUIWriteBaseline!
)
).toEqual({ hideDefaultBranchWorkspace: true })
expect(vi.getTimerCount()).toBe(0)
// A new edit explicitly flushes both its change and the previous dirty field.
rejectSets = false
act(() => {
store.getState().setHideCliCreatedWorkspaces(true)
})
vi.advanceTimersByTime(150)
await Promise.resolve()
expect(setCallCount).toBe(2)
expect(authority.get().hideDefaultBranchWorkspace).toBe(true)
expect(authority.get().hideCliCreatedWorkspaces).toBe(true)
expect(store.getState().persistedUIWriteInFlightCounts).toEqual({})
// Unmount must cancel delayed work and prevent later store writes.
act(() => {
root.unmount()
})
expect(vi.getTimerCount()).toBe(0)
store.getState().setHideDetachedHeadWorkspaces(true)
vi.advanceTimersByTime(300)
expect(setCallCount).toBe(2)
expect(vi.getTimerCount()).toBe(0)
})
it('a transient rejection still flushes a pending flip-back exactly once', async () => {
// A newer pending edit still deserves one trailing flush after rejection; rejection alone does not.
holdAcks = true
rejectNextSet = true
setCallCount = 0
act(() => {
store.getState().setHideDefaultBranchWorkspace(true)
})
vi.advanceTimersByTime(150)
expect(setCallCount).toBe(1)
expect(pendingRejects).toHaveLength(1)
// Flip back and edit another field in flight; only newer edits authorize the trailing pass.
act(() => {
store.getState().setHideDefaultBranchWorkspace(false)
store.getState().setHideCliCreatedWorkspaces(true)
})
holdAcks = false
pendingRejects.splice(0).forEach((reject) => reject(new Error('transient transport failure')))
expect(pendingRejects).toHaveLength(0)
await Promise.resolve()
vi.advanceTimersByTime(150)
await Promise.resolve()
expect(setCallCount).toBe(2)
expect(authority.get().hideDefaultBranchWorkspace).toBe(false)
expect(authority.get().hideCliCreatedWorkspaces).toBe(true)
expect(store.getState().persistedUIWriteInFlightCounts).toEqual({})
vi.advanceTimersByTime(150)
await Promise.resolve()
expect(setCallCount).toBe(2)
expect(vi.getTimerCount()).toBe(0)
})
it('a rejected trailing write does not inherit automatic retry permission', async () => {
// A trailing attempt rejected without newer edits is terminal too.
holdAcks = true
setCallCount = 0
act(() => {
store.getState().setHideDefaultBranchWorkspace(true)
})
vi.advanceTimersByTime(150)
expect(setCallCount).toBe(1)
act(() => {
store.getState().setHideCliCreatedWorkspaces(true)
})
await resolveAcks()
holdAcks = false
rejectSets = true
// Overlapping debounce/ack scheduling must yield only one rejected trailing attempt.
vi.advanceTimersByTime(150)
await Promise.resolve()
expect(setCallCount).toBe(2)
expect(store.getState().persistedUIWriteInFlightCounts).toEqual({})
vi.advanceTimersByTime(150)
await Promise.resolve()
expect(setCallCount).toBe(2)
expect(vi.getTimerCount()).toBe(0)
})
it('a synchronously throwing ui.set settles without a retry loop', async () => {
const api = (
window as unknown as { api: { ui: { set: (u: Partial<PersistedUIState>) => Promise<void> } } }
).api.ui
const workingSet = api.set
api.set = () => {
setCallCount += 1
throw new Error('non-cloneable argument')
}
act(() => {
store.getState().setHideDefaultBranchWorkspace(true)
})
await flushDesktopDebounce()
// A leaked marker would pin the field against hydration for the renderer's life.
expect(store.getState().persistedUIWriteInFlightCounts).toEqual({})
// Recovery is explicit: a later edit flushes the still-dirty field.
api.set = workingSet
act(() => {
store.getState().setHideCliCreatedWorkspaces(true)
})
await flushDesktopDebounce()
expect(authority.get().hideDefaultBranchWorkspace).toBe(true)
})
})
@@ -143,7 +143,6 @@ vi.mock('@/store', () => {
return { useAppStore }
})
// Paste encoding is under test here; owner routing is covered by AgentTerminalPreview.test.tsx.
vi.mock('./terminal-preview-api', () => ({
terminalPreviewApiFor: () => window.api.terminalPreview
}))
@@ -1,387 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import type { ITerminalOptions } from '@xterm/xterm'
import { act, cleanup, render, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { TerminalPreviewApi } from '../../../../preload/api/dashboard-api'
import type { TerminalPreviewConnectResult } from '../../../../shared/terminal/replay/terminal-preview'
const terminalHarness = vi.hoisted(() => ({
instances: [] as {
write: ReturnType<typeof vi.fn>
writeCallbacks: (() => void)[]
onDataListener: ((data: string) => void) | null
dispose: ReturnType<typeof vi.fn>
resize: ReturnType<typeof vi.fn>
reset: ReturnType<typeof vi.fn>
paste: ReturnType<typeof vi.fn>
input: ReturnType<typeof vi.fn>
scrollToTop: ReturnType<typeof vi.fn>
scrollToBottom: ReturnType<typeof vi.fn>
selectAll: ReturnType<typeof vi.fn>
modes: { bracketedPasteMode: boolean }
selectionText: string
customKeyHandler: ((event: KeyboardEvent) => boolean) | null
}[],
userInputListener: null as (() => void) | null,
userInputDispose: vi.fn()
}))
const platformState = vi.hoisted(() => ({ value: 'linux' }))
const storeState = vi.hoisted(() => ({
settings: null,
keybindings: {} as Record<string, string[]>
}))
const imeHarness = vi.hoisted(() => ({
forwarders: [] as {
claimKeyEvent: ReturnType<typeof vi.fn>
dispose: ReturnType<typeof vi.fn>
sendInput: (data: string) => void
getKittyKeyboardFlags: () => number
}[],
trackers: [] as { dispose: ReturnType<typeof vi.fn> }[],
claimResult: false
}))
vi.mock('@xterm/xterm', () => ({
Terminal: class {
cols = 80
rows = 24
buffer = { active: { cursorY: 0 } }
writeCallbacks: (() => void)[] = []
onDataListener: ((data: string) => void) | null = null
customKeyHandler: ((event: KeyboardEvent) => boolean) | null = null
selectionText = ''
write = vi.fn((_data: string, callback?: () => void) => {
if (callback) {
this.writeCallbacks.push(callback)
}
})
open = vi.fn()
focus = vi.fn()
dispose = vi.fn()
resize = vi.fn()
reset = vi.fn()
modes = { bracketedPasteMode: false }
paste = vi.fn((data: string) => {
terminalHarness.userInputListener?.()
this.onDataListener?.(data)
})
input = vi.fn((data: string) => {
terminalHarness.userInputListener?.()
this.onDataListener?.(data)
})
element = document.createElement('div')
unicode = { activeVersion: '6', versions: ['6', '11'], register: vi.fn() }
loadAddon = vi.fn()
options: ITerminalOptions = {}
attachCustomWheelEventHandler = vi.fn()
scrollToTop = vi.fn()
scrollToBottom = vi.fn()
selectAll = vi.fn()
getSelection = vi.fn(() => this.selectionText)
hasSelection = vi.fn(() => this.selectionText !== '')
attachCustomKeyEventHandler = vi.fn((handler: (event: KeyboardEvent) => boolean) => {
this.customKeyHandler = handler
})
onData = vi.fn((listener: (data: string) => void) => {
this.onDataListener = listener
return { dispose: vi.fn() }
})
constructor() {
terminalHarness.instances.push(this)
}
}
}))
vi.mock(import('@/lib/pane-manager/pane-terminal-options'), async (importOriginal) => ({
...(await importOriginal()),
buildDefaultTerminalOptions: () => ({})
}))
vi.mock('@/components/terminal-pane/input/terminal-user-input-signal', () => ({
subscribeToTerminalUserInput: (_terminal: unknown, listener: () => void) => {
terminalHarness.userInputListener = listener
return { dispose: terminalHarness.userInputDispose }
}
}))
vi.mock('@/hooks/theme/use-system-prefers-dark', () => ({
useSystemPrefersDark: () => false
}))
vi.mock('@/lib/keyboard/shortcut-platform', () => ({
getShortcutPlatform: () => platformState.value
}))
vi.mock('@/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder', () => ({
installTerminalImeNativeTextForwarder: (args: {
sendInput: (data: string) => void
getKittyKeyboardFlags?: () => number
}) => {
const forwarder = {
claimKeyEvent: vi.fn(() => imeHarness.claimResult),
dispose: vi.fn(),
sendInput: args.sendInput,
// Read the same live keyboard-mode mirror the real commit forwarder receives.
getKittyKeyboardFlags: args.getKittyKeyboardFlags ?? ((): number => 0)
}
imeHarness.forwarders.push(forwarder)
return forwarder
}
}))
vi.mock('@/components/terminal-pane/input/ime/terminal-ime-composition-tracker', () => ({
installTerminalImeCompositionTracker: () => {
const tracker = { isActive: () => false, dispose: vi.fn() }
imeHarness.trackers.push(tracker)
return tracker
}
}))
vi.mock('@/store', () => {
const useAppStore = (selector: (s: typeof storeState) => unknown): unknown => selector(storeState)
useAppStore.getState = (): typeof storeState => storeState
return { useAppStore }
})
type RemotePreviewSubscription = {
terminal: string
callbacks: {
onSnapshot: (data: string, meta?: { cols?: number; rows?: number; seq?: number }) => void
onData: (data: string, meta?: { seq?: number }) => void
}
}
const multiplexerHarness = vi.hoisted(() => {
const environments: string[] = []
const subscriptions: RemotePreviewSubscription[] = []
return { environments, subscriptions, sendInput: vi.fn(() => true), close: vi.fn() }
})
vi.mock(
'@/runtime/hosted-terminals/streams/registry/remote-runtime-terminal-multiplexer-registry',
() => ({
getRemoteRuntimeTerminalMultiplexer: (environmentId: string) => {
multiplexerHarness.environments.push(environmentId)
return {
subscribeTerminal: async (args: RemotePreviewSubscription) => {
multiplexerHarness.subscriptions.push(args)
return {
sendInput: multiplexerHarness.sendInput,
claimViewport: vi.fn(() => true),
close: multiplexerHarness.close
}
}
}
}
})
)
import { AgentTerminalPreview } from './AgentTerminalPreview'
import { resetRemoteRuntimeTerminalPreviewSessionsForTests } from './remote-runtime-terminal-preview-api'
describe('AgentTerminalPreview', () => {
const input = vi.fn(async (_ptyId: string, _data: string) => true)
const fit = vi.fn(async (_ptyId: string, cols: number, rows: number) => ({ cols, rows }))
const ack = vi.fn(async () => {})
const unsubscribe = vi.fn(async () => {})
const connect = vi.fn<TerminalPreviewApi['connect']>()
const readClipboardText = vi.fn(async () => 'clip-text')
const writeClipboardText = vi.fn(async () => {})
const writeTerminalClipboardText = vi.fn(async () => {})
let emitData: ((payload: unknown) => void) | null
beforeEach(() => {
terminalHarness.instances.length = 0
terminalHarness.userInputListener = null
platformState.value = 'linux'
storeState.keybindings = {}
imeHarness.forwarders.length = 0
imeHarness.trackers.length = 0
imeHarness.claimResult = false
emitData = null
connect.mockResolvedValue({
snapshot: { data: '', cols: 80, rows: 24, seq: 1 },
replay: []
})
readClipboardText.mockResolvedValue('clip-text')
Object.assign(window, {
api: {
terminalPreview: {
connect,
input,
fit,
ack,
unsubscribe,
onData: (listener: (payload: unknown) => void) => {
emitData = listener
return vi.fn()
}
},
ui: {
readClipboardText,
writeClipboardText,
writeTerminalClipboardText,
performNativeSelectionAction: vi.fn()
}
}
})
})
afterEach(() => {
cleanup()
vi.useRealTimers()
resetRemoteRuntimeTerminalPreviewSessionsForTests()
multiplexerHarness.environments.length = 0
multiplexerHarness.subscriptions.length = 0
vi.clearAllMocks()
})
it('routes signaled user input while a live write parses and drops parser replies', async () => {
render(<AgentTerminalPreview ptyId="pty-1" />)
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
const terminal = terminalHarness.instances[0]!
await waitFor(() => expect(terminal.onDataListener).not.toBeNull())
act(() => {
emitData?.({ type: 'data', ptyId: 'pty-1', data: '\x1b[6n', bytes: 4 })
})
expect(terminal.write).toHaveBeenCalledWith('\x1b[6n', expect.any(Function))
act(() => {
terminalHarness.userInputListener?.()
terminal.onDataListener?.('k')
terminal.onDataListener?.('\x1b[1;1R')
})
expect(input).toHaveBeenCalledTimes(1)
expect(input).toHaveBeenCalledWith('pty-1', 'k')
// Why drain all: the connection's kitty restore write queues ahead of the live chunk.
act(() => terminal.writeCallbacks.splice(0).forEach((callback) => callback()))
expect(ack).toHaveBeenCalledWith('pty-1', 4)
})
it('keeps a native input-source chord from inserting text into the preview', async () => {
storeState.keybindings = { 'terminal.switchInputSource': ['Shift+Space'] }
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
const terminal = terminalHarness.instances[0]!
await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull())
const keydown = new KeyboardEvent('keydown', {
key: ' ',
code: 'Space',
shiftKey: true,
bubbles: true,
cancelable: true
})
expect(terminal.customKeyHandler!(keydown)).toBe(false)
expect(keydown.defaultPrevented).toBe(false)
const keypress = new KeyboardEvent('keypress', {
key: ' ',
bubbles: true,
cancelable: true
})
window.dispatchEvent(keypress)
expect(keypress.defaultPrevented).toBe(true)
const beforeInput = new InputEvent('beforeinput', {
data: ' ',
inputType: 'insertText',
bubbles: true,
cancelable: true
})
window.dispatchEvent(beforeInput)
expect(beforeInput.defaultPrevented).toBe(true)
window.dispatchEvent(new KeyboardEvent('keyup', { key: ' ', code: 'Space', bubbles: true }))
const unarmedBeforeInput = new InputEvent('beforeinput', {
data: ' ',
inputType: 'insertText',
bubbles: true,
cancelable: true
})
window.dispatchEvent(unarmedBeforeInput)
expect(unarmedBeforeInput.defaultPrevented).toBe(false)
expect(terminal.input).not.toHaveBeenCalled()
expect(input).not.toHaveBeenCalled()
view.unmount()
})
// Snapshot replay can redeliver a kitty push; it must not leave stale flags after the TUI’s single pop.
it('does not let a redelivered kitty push outlive the TUI pop', async () => {
connect.mockResolvedValueOnce({
snapshot: { data: '\x1b[>1u', cols: 80, rows: 24, seq: 1 },
replay: [{ data: '\x1b[>1u', mode: 'replay' }]
})
render(<AgentTerminalPreview ptyId="pty-1" />)
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
const terminal = terminalHarness.instances[0]!
await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull())
const altBackspace = (): KeyboardEvent =>
new KeyboardEvent('keydown', { key: 'Backspace', code: 'Backspace', altKey: true })
expect(terminal.customKeyHandler!(altBackspace())).toBe(true)
// The TUI exits and pops once on the live stream.
act(() => {
emitData?.({ type: 'data', ptyId: 'pty-1', data: '\x1b[<u', bytes: 4 })
})
expect(terminal.customKeyHandler!(altBackspace())).toBe(false)
expect(terminal.input).toHaveBeenCalledWith('\x1b\x7f')
})
it('keeps the existing terminal visible while a resync snapshot is captured', async () => {
let resolveRefresh!: (value: TerminalPreviewConnectResult) => void
connect
.mockResolvedValueOnce({
snapshot: { data: 'first', cols: 80, rows: 24, seq: 1 },
replay: []
})
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveRefresh = resolve
})
)
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
const terminal = terminalHarness.instances[0]!
act(() => emitData?.({ type: 'resync', ptyId: 'pty-1' }))
await waitFor(() => expect(connect).toHaveBeenCalledTimes(2))
expect(terminalHarness.instances).toHaveLength(1)
expect(terminal.dispose).not.toHaveBeenCalled()
expect(terminal.reset).not.toHaveBeenCalled()
expect(view.queryByText(/No preview available/)).not.toBeInTheDocument()
await act(async () => {
resolveRefresh({
snapshot: { data: 'second', cols: 100, rows: 30, seq: 2 },
replay: []
})
})
await waitFor(() => expect(terminal.reset).toHaveBeenCalledTimes(1))
expect(terminal.resize).toHaveBeenCalledWith(100, 30)
expect(terminalHarness.instances).toHaveLength(1)
expect(terminal.dispose).not.toHaveBeenCalled()
expect(view.queryByText(/No preview available/)).not.toBeInTheDocument()
})
it('disposes a stale terminal when resync confirms the pty is gone', async () => {
connect
.mockResolvedValueOnce({
snapshot: { data: 'first', cols: 80, rows: 24, seq: 1 },
replay: []
})
.mockResolvedValueOnce({ snapshot: null, replay: [] })
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
const terminal = terminalHarness.instances[0]!
act(() => emitData?.({ type: 'resync', ptyId: 'pty-1' }))
await waitFor(() => expect(view.getByText(/No preview available/)).toBeInTheDocument())
expect(terminal.dispose).toHaveBeenCalledTimes(1)
expect(terminalHarness.userInputDispose).toHaveBeenCalledTimes(1)
expect(unsubscribe).toHaveBeenCalledWith('pty-1')
})
})
@@ -1,387 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
useIpcEventsForCloseRouting,
type RequestTabCloseListener,
type CloseActiveTabListener,
type CloseSessionTabListener,
type TerminalTabCloseRequestListener
} from './ipc-events-close-routing-test-harness'
const { closeTerminalTabMock } = vi.hoisted(() => ({
closeTerminalTabMock: vi.fn()
}))
vi.mock('@/components/terminal/terminal-tab-actions', () => ({
closeTerminalTab: closeTerminalTabMock
}))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (original) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await original())
)
vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (original) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await original())
)
describe('useIpcEvents browser tab close routing', () => {
beforeEach(() => {
vi.resetModules()
vi.unstubAllGlobals()
// Clear leaked partial mocks so floating browser source validation uses the real resolver.
vi.doUnmock('@/components/floating-terminal/floating-workspace-terminal-actions')
vi.doUnmock('@/components/floating-terminal/floating-workspace-tab-creation')
closeTerminalTabMock.mockReset()
})
it('removes the file from openFiles when a companion closes an editor session tab', async () => {
const closeSessionTabListenerRef: { current: CloseSessionTabListener | null } = {
current: null
}
const { createEditorTabsStore } =
await import('../store/slices/editor/editor-slice-test-harness')
const store = createEditorTabsStore()
await useIpcEventsForCloseRouting({
closeSessionTabListenerRef,
getState: store.getState
})
const fileId = store.getState().openFile({
filePath: '/repo/file.ts',
relativePath: 'file.ts',
worktreeId: 'wt-1',
language: 'typescript',
mode: 'edit'
})
const tab = store.getState().unifiedTabsByWorktree['wt-1']?.find((t) => t.entityId === fileId)
expect(tab).toBeDefined()
closeSessionTabListenerRef.current?.({ tabId: tab!.id, worktreeId: 'wt-1' })
await vi.waitFor(() => {
expect(store.getState().unifiedTabsByWorktree['wt-1']).toEqual([])
expect(store.getState().openFiles).toEqual([])
})
})
it('acknowledges whole-tab close only after the fresh session is durably persisted', async () => {
const listenerRef: { current: TerminalTabCloseRequestListener | null } = { current: null }
let finishPersist!: () => void
const persistWorkspaceSession = vi.fn(
() =>
new Promise<void>((resolve) => {
finishPersist = resolve
})
)
const respondTerminalTabClose = vi.fn()
closeTerminalTabMock.mockImplementation((_tabId: string, options: { onClosed?: () => void }) =>
options.onClosed?.()
)
await useIpcEventsForCloseRouting({
getState: () => ({}),
terminalTabCloseRequestListenerRef: listenerRef,
respondTerminalTabClose,
persistWorkspaceSession
})
listenerRef.current?.({
requestId: 'close-1',
tabId: 'terminal-1',
localPtyTeardownOwnedExternally: true,
force: true
})
await Promise.resolve()
expect(closeTerminalTabMock).toHaveBeenCalledWith(
'terminal-1',
expect.objectContaining({
rejectPinned: true,
force: true,
localPtyTeardownOwnedExternally: true
})
)
expect(persistWorkspaceSession).toHaveBeenCalledTimes(1)
expect(respondTerminalTabClose).not.toHaveBeenCalled()
finishPersist()
await vi.waitFor(() =>
expect(respondTerminalTabClose).toHaveBeenCalledWith({ requestId: 'close-1' })
)
})
it('rejects a pinned whole-tab close without persisting or reporting success', async () => {
const listenerRef: { current: TerminalTabCloseRequestListener | null } = { current: null }
const persistWorkspaceSession = vi.fn().mockResolvedValue(undefined)
const respondTerminalTabClose = vi.fn()
closeTerminalTabMock.mockImplementation((_tabId: string, options: { onCancel?: () => void }) =>
options.onCancel?.()
)
await useIpcEventsForCloseRouting({
getState: () => ({}),
terminalTabCloseRequestListenerRef: listenerRef,
respondTerminalTabClose,
persistWorkspaceSession
})
listenerRef.current?.({ requestId: 'close-pinned', tabId: 'terminal-pinned' })
expect(persistWorkspaceSession).not.toHaveBeenCalled()
expect(respondTerminalTabClose).toHaveBeenCalledWith({
requestId: 'close-pinned',
error: 'terminal_tab_pinned'
})
})
it('confirms before closing a pinned active browser tab from the native close event', async () => {
const closeActiveTabListenerRef: { current: CloseActiveTabListener | null } = { current: null }
const closeBrowserTab = vi.fn()
const requestPinnedTabCloseConfirm = vi.fn()
await useIpcEventsForCloseRouting({
closeActiveTabListenerRef,
getState: () => ({
recordClientHostedBrowserCloseIntents: vi.fn(),
closeBrowserTab,
requestPinnedTabCloseConfirm,
unifiedTabsByWorktree: {
'wt-1': [
{
id: 'browser-unified-1',
entityId: 'workspace-1',
contentType: 'browser',
label: 'Docs',
isPinned: true
}
]
}
})
})
closeActiveTabListenerRef.current?.()
expect(closeBrowserTab).not.toHaveBeenCalled()
expect(requestPinnedTabCloseConfirm).toHaveBeenCalledWith(
expect.objectContaining({ tabLabel: 'Docs', onConfirm: expect.any(Function) })
)
const { onConfirm } = requestPinnedTabCloseConfirm.mock.calls[0][0] as { onConfirm: () => void }
onConfirm()
expect(closeBrowserTab).toHaveBeenCalledWith('workspace-1', undefined)
})
it('confirms CLI workspace browser closes and replies after confirmation', async () => {
const requestTabCloseListenerRef: { current: RequestTabCloseListener | null } = {
current: null
}
const closeBrowserTab = vi.fn()
const replyTabClose = vi.fn()
const requestPinnedTabCloseConfirm = vi.fn()
await useIpcEventsForCloseRouting({
requestTabCloseListenerRef,
replyTabClose,
getState: () => ({
recordClientHostedBrowserCloseIntents: vi.fn(),
closeBrowserTab,
requestPinnedTabCloseConfirm,
unifiedTabsByWorktree: {
'wt-1': [
{
id: 'browser-unified-1',
entityId: 'workspace-1',
contentType: 'browser',
label: 'Docs',
isPinned: true
}
]
}
})
})
requestTabCloseListenerRef.current?.({ requestId: 'req-pinned', tabId: 'workspace-1' })
expect(closeBrowserTab).not.toHaveBeenCalled()
expect(replyTabClose).not.toHaveBeenCalledWith({ requestId: 'req-pinned' })
const request = requestPinnedTabCloseConfirm.mock.calls[0][0] as {
onConfirm: () => void
onCancel: () => void
}
request.onConfirm()
expect(closeBrowserTab).toHaveBeenCalledWith('workspace-1')
expect(replyTabClose).toHaveBeenCalledWith({ requestId: 'req-pinned' })
})
it('replies with the pinned error when a CLI browser close is canceled', async () => {
const requestTabCloseListenerRef: { current: RequestTabCloseListener | null } = {
current: null
}
const closeBrowserTab = vi.fn()
const replyTabClose = vi.fn()
const requestPinnedTabCloseConfirm = vi.fn()
await useIpcEventsForCloseRouting({
requestTabCloseListenerRef,
replyTabClose,
getState: () => ({
recordClientHostedBrowserCloseIntents: vi.fn(),
closeBrowserTab,
requestPinnedTabCloseConfirm,
unifiedTabsByWorktree: {
'wt-1': [
{
id: 'browser-unified-1',
entityId: 'workspace-1',
contentType: 'browser',
label: 'Docs',
isPinned: true
}
]
}
})
})
requestTabCloseListenerRef.current?.({ requestId: 'req-cancel', tabId: 'workspace-1' })
const request = requestPinnedTabCloseConfirm.mock.calls[0][0] as {
onCancel: () => void
}
request.onCancel()
expect(closeBrowserTab).not.toHaveBeenCalled()
expect(replyTabClose).toHaveBeenCalledWith({
requestId: 'req-cancel',
error: 'Browser tab workspace-1 is pinned'
})
})
it('lets CLI browser closes bypass confirmation when the pinned-tab setting is off', async () => {
const requestTabCloseListenerRef: { current: RequestTabCloseListener | null } = {
current: null
}
const closeBrowserTab = vi.fn()
const replyTabClose = vi.fn()
const requestPinnedTabCloseConfirm = vi.fn()
await useIpcEventsForCloseRouting({
requestTabCloseListenerRef,
replyTabClose,
getState: () => ({
recordClientHostedBrowserCloseIntents: vi.fn(),
closeBrowserTab,
requestPinnedTabCloseConfirm,
settings: {
activeRuntimeEnvironmentId: null,
confirmClosePinnedTab: false,
terminalFontSize: 13
},
unifiedTabsByWorktree: {
'wt-1': [
{
id: 'browser-unified-1',
entityId: 'workspace-1',
contentType: 'browser',
label: 'Docs',
isPinned: true
}
]
}
})
})
requestTabCloseListenerRef.current?.({ requestId: 'req-off', tabId: 'workspace-1' })
expect(requestPinnedTabCloseConfirm).not.toHaveBeenCalled()
expect(closeBrowserTab).toHaveBeenCalledWith('workspace-1')
expect(replyTabClose).toHaveBeenCalledWith({ requestId: 'req-off' })
})
it('guards a CLI last-page close for a pinned browser workspace', async () => {
const requestTabCloseListenerRef: { current: RequestTabCloseListener | null } = {
current: null
}
const closeBrowserTab = vi.fn()
const closeBrowserPage = vi.fn()
const replyTabClose = vi.fn()
const requestPinnedTabCloseConfirm = vi.fn()
await useIpcEventsForCloseRouting({
requestTabCloseListenerRef,
replyTabClose,
getState: () => ({
recordClientHostedBrowserCloseIntents: vi.fn(),
closeBrowserTab,
closeBrowserPage,
requestPinnedTabCloseConfirm,
browserPagesByWorkspace: {
'workspace-1': [{ id: 'page-1', workspaceId: 'workspace-1' }]
},
unifiedTabsByWorktree: {
'wt-1': [
{
id: 'browser-unified-1',
entityId: 'workspace-1',
contentType: 'browser',
label: 'Docs',
isPinned: true
}
]
}
})
})
requestTabCloseListenerRef.current?.({ requestId: 'req-page', tabId: 'page-1' })
expect(closeBrowserPage).not.toHaveBeenCalled()
expect(closeBrowserTab).not.toHaveBeenCalled()
expect(requestPinnedTabCloseConfirm).toHaveBeenCalledWith(
expect.objectContaining({ tabLabel: 'Docs', onConfirm: expect.any(Function) })
)
})
it('refuses to close a browser page outside the requested worktree', async () => {
const requestTabCloseListenerRef: { current: RequestTabCloseListener | null } = {
current: null
}
const closeBrowserTab = vi.fn()
const closeBrowserPage = vi.fn()
const replyTabClose = vi.fn()
await useIpcEventsForCloseRouting({
requestTabCloseListenerRef,
replyTabClose,
getState: () => ({
recordClientHostedBrowserCloseIntents: vi.fn(),
closeBrowserTab,
closeBrowserPage,
browserTabsByWorktree: {
'wt-1': [{ id: 'workspace-1' }],
'wt-2': [{ id: 'workspace-2' }]
},
browserPagesByWorkspace: {
'workspace-1': [{ id: 'page-1', workspaceId: 'workspace-1' }],
'workspace-2': [{ id: 'page-2', workspaceId: 'workspace-2' }]
}
})
})
requestTabCloseListenerRef.current?.({
requestId: 'req-wrong-worktree',
tabId: 'page-2',
worktreeId: 'wt-1'
})
expect(closeBrowserPage).not.toHaveBeenCalled()
expect(closeBrowserTab).not.toHaveBeenCalled()
expect(replyTabClose).toHaveBeenCalledWith({
requestId: 'req-wrong-worktree',
code: 'browser_tab_not_found',
error: 'Browser tab page-2 not found'
})
})
})
@@ -24,16 +24,6 @@ describe('Codex fullscreen composer paste gate', () => {
expect(scanner.observe(END).ready).toBe(true)
})
it.each([']', 'P', 'X', '^', '_'])('keeps split ESC %s control strings hidden', (kind) => {
const scanner = createDraftPasteReadyScanner('codex-composer-prompt')
scanner.observe(PROVISIONAL)
const payload = `\x1b${kind}${'x'.repeat(1024)}\x1b[39;3HModel · folder\x1b\\`
for (const char of payload) {
expect(scanner.observe(char).ready).toBe(false)
}
expect(scanner.observe(LIVE).ready).toBe(true)
})
it('takes Codex’s idle report when its status line paints no footer row', () => {
const scanner = createDraftPasteReadyScanner('codex-composer-prompt')
expect(scanner.observe(PROVISIONAL).ready).toBe(false)
@@ -1,56 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { AgentSessionSlashCommand } from '../../agent-session/agent-session-wire'
import type { DiscoveredSkill } from '../../skills'
import { buildNativeChatPickerItems } from './native-chat-picker-items'
import { sessionReportedSkills, sessionSlashCommandSuggestions } from './native-chat-slash-commands'
const scannedDemo: DiscoveredSkill = {
id: 'home:demo',
name: 'demo',
description: 'Demo skill',
providers: ['claude'],
sourceKind: 'home',
sourceLabel: 'Home',
rootPath: '/home/u/.claude/skills',
directoryPath: '/home/u/.claude/skills/demo',
skillFilePath: '/home/u/.claude/skills/demo/SKILL.md',
installed: true,
updatedAt: null
}
function skillHints(reported: AgentSessionSlashCommand[]): Record<string, string | undefined> {
const items = buildNativeChatPickerItems(
sessionSlashCommandSuggestions('claude', reported),
[scannedDemo],
'',
'/',
sessionReportedSkills(reported, 'claude')
)
return Object.fromEntries(
items.flatMap((item) => (item.kind === 'skill' ? [[item.name, item.argumentHint]] : []))
)
}
describe('skill argument hints in the native chat picker', () => {
it('shows the hint the session reports for a skill', () => {
expect(
skillHints([
{ name: 'demo', kind: 'skill', argumentHint: '<target>' },
{
name: 'plan',
kind: 'skill',
argumentHint: '[plan|implement] [ref ...]',
path: '/home/u/.claude/skills/plan/SKILL.md'
}
])
).toEqual({ demo: '<target>', plan: '[plan|implement] [ref ...]' })
})
it('keeps the hint before the session has classified its catalog', () => {
expect(
skillHints([
{ name: 'demo', kind: 'command', kindUnspecified: true, argumentHint: '<target>' }
])
).toEqual({ demo: '<target>' })
})
})
@@ -1,177 +0,0 @@
// @vitest-environment happy-dom
import { resolveHiddenProbeCwd } from '../../src/main/lib/hidden-probe-cwd'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => ({ call: vi.fn(), cli: vi.fn() }))
vi.mock(
'../../src/renderer/src/runtime/native-chat/requests/structured-agent-session-call',
() => ({
callStructuredAgentSession: mocks.call
})
)
vi.mock('@/runtime/source-control/git/runtime-git-generation-client', () => ({
discoverRuntimeCommitMessageModels: mocks.cli
}))
vi.mock('@/runtime/hosts/capabilities/local-runtime-capabilities', () => ({
subscribeLocalRuntimeCapabilitiesKnown: () => () => {},
ensureLocalRuntimeCapabilities: async () => [],
readLocalRuntimeCapabilitiesOrUnknown: () => []
}))
import type { AgentModelCatalogProbe } from '../../src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery'
import { createAgentModelCatalogService } from '../../src/main/native-chat/agent-model-catalog/agent-model-catalog-service'
import { AgentModelCatalogStore } from '../../src/main/native-chat/agent-model-catalog/agent-model-catalog-store'
import {
readHostModelCatalogSnapshot,
recordHostModelCatalogSnapshot,
resetHostModelCatalogSnapshotsForTests
} from '../../src/renderer/src/runtime/native-chat/model-catalogs/host-model-catalog-snapshots'
const LOCAL = { kind: 'local' } as const
const NEW_CHAT = { newLaunch: true, worktree: 'wt-1', seedsModel: false }
function hostCatalog(agent: 'claude' | 'codex', store = new AgentModelCatalogStore()) {
let held = false
const entered = Promise.withResolvers<void>()
const scope = Promise.withResolvers<void>()
const resolveAccountHome = vi.fn(async () => ({
variable: 'HOME',
path: '/pr-36646-account'
}))
const listing = {
origin: 'probe' as const,
complete: true,
configured: { model: 'account-model', effort: 'high' },
models: [
{
id: 'account-model',
label: 'Account model',
isDefault: true,
efforts: [{ value: 'high', label: 'High' }],
defaultEffort: 'high',
declaredDefaultEffort: 'high'
}
]
}
const run = vi.fn(async () => listing)
const probe = Object.assign(run, {
resolve: vi.fn<NonNullable<AgentModelCatalogProbe['resolve']>>(async (_home, cwd) => {
if (held) {
entered.resolve()
await scope.promise
}
return { identity: { command: agent, cwd }, run }
})
})
const service = createAgentModelCatalogService({
store,
getConversation: () => undefined,
getRecord: () => undefined,
drivesRecord: () => true,
resolveAccountHome,
probes: { [agent]: probe }
})
return {
service,
store,
probe,
listing,
resolveAccountHome,
entered,
scope,
hold: () => {
held = true
}
}
}
describe('account catalog to renderer cache', () => {
beforeEach(() => {
resetHostModelCatalogSnapshotsForTests()
mocks.call.mockReset()
mocks.cli.mockReset()
})
it.each(['claude', 'codex'] as const)(
'keeps %s provisional saved-only answers scoped while exact resolution is held',
async (agent) => {
const first = hostCatalog(agent)
await first.service.read({ agent, waitForListing: true })
expect(first.probe).toHaveBeenCalledTimes(1)
first.service.stop()
const { service, probe, resolveAccountHome, entered, scope, hold } = hostCatalog(
agent,
first.store
)
try {
expect(service.snapshot({ agent })).toEqual({ origin: 'unknown' })
hold()
const refresh = service.demand({ agent })
await entered.promise
const resolutions = probe.resolve.mock.calls.length
const homeResolutions = resolveAccountHome.mock.calls.length
const publish = vi.spyOn(first.store, 'recordSuccess')
const answers = [
service.snapshot({ agent }),
service.snapshot({ agent, savedOnly: true }),
await service.read({ agent }),
await service.read({ agent, savedOnly: true }),
await service.prepareSaved({ agent })
]
for (const answer of answers) {
expect(answer).toMatchObject({
modelsDifferByWorkspace: true,
listingNamesConfiguredModel: false,
models: [{ id: 'account-model', isDefault: false }]
})
if (answer.origin === 'unknown') {
throw new Error('missing provisional inventory')
}
expect(answer.models[0]).not.toHaveProperty('defaultEffort')
expect(answer.models[0]).not.toHaveProperty('declaredDefaultEffort')
recordHostModelCatalogSnapshot(LOCAL, agent, null, answer)
for (const newLaunch of [false, true]) {
for (const seedsModel of [false, true]) {
expect(
readHostModelCatalogSnapshot(LOCAL, agent, {
newLaunch,
seedsModel,
worktree: 'restricted'
})
).toBeUndefined()
}
}
}
expect(service.snapshot({ agent, verifiedOnly: true })).toEqual({ origin: 'unknown' })
expect(await service.read({ agent, savedOnly: true, verifiedOnly: true })).toEqual({
origin: 'unknown'
})
expect(probe.resolve).toHaveBeenCalledTimes(resolutions)
expect(resolveAccountHome).toHaveBeenCalledTimes(homeResolutions)
expect(probe).not.toHaveBeenCalled()
expect(publish).not.toHaveBeenCalled()
scope.resolve()
await refresh
expect(probe.resolve.mock.calls.every(([, cwd]) => cwd === resolveHiddenProbeCwd())).toBe(
true
)
const exact = service.snapshot({ agent, verifiedOnly: true })
expect(exact).toMatchObject({
models: [{ id: 'account-model', isDefault: true, declaredDefaultEffort: 'high' }]
})
recordHostModelCatalogSnapshot(LOCAL, agent, 'own-folder', exact)
expect(
readHostModelCatalogSnapshot(LOCAL, agent, { ...NEW_CHAT, worktree: 'own-folder' })
).toEqual(exact)
expect(
readHostModelCatalogSnapshot(LOCAL, agent, { ...NEW_CHAT, worktree: 'restricted' })
).toBeUndefined()
} finally {
scope.resolve()
service.stop()
}
}
)
})
@@ -1,167 +0,0 @@
// Relay the server browser’s tab and real screencast frames through a desktop to its paired phone.
import { expect, test } from './helpers/orca-app'
import { launchPhoneMirrorTopology } from './helpers/phone-mirror-topology'
import type { PairedMobileSocket } from './helpers/paired-mobile-client'
import { z } from 'zod'
type Frame = PairedMobileSocket['frames'][number]
const HostWorktreesSchema = z.looseObject({
worktrees: z.array(z.looseObject({ worktreeId: z.string(), path: z.string() }))
})
const CreatedSchema = z.looseObject({ browserPageId: z.string() })
const TabsSchema = z.looseObject({
tabs: z.array(z.looseObject({ type: z.string(), browserPageId: z.string().optional() }))
})
const ReadySchema = z.looseObject({ type: z.literal('ready'), subscriptionId: z.string() })
const JPEG_MAGIC = [0xff, 0xd8, 0xff]
let requestCount = 0
function nextId(label: string): string {
requestCount += 1
return `${label}-${requestCount}`
}
async function reply(socket: PairedMobileSocket, id: string, timeout = 30_000): Promise<Frame> {
const find = (): Frame | undefined => socket.frames.find((frame) => frame.id === id)
await expect.poll(find, { timeout }).toBeDefined()
const found = find()
if (!found) {
throw new Error(`no reply to ${id}`)
}
return found
}
async function call<T>(
socket: PairedMobileSocket,
request: { id: string; method: string; params: unknown; executionHost: string },
schema: z.ZodType<T>
): Promise<T> {
socket.send(request.id, request.method, request.params, request.executionHost)
const frame = await reply(socket, request.id)
expect(frame.ok, `${request.method}: ${JSON.stringify(frame.error)}`).toBe(true)
return schema.parse(frame.result)
}
test('phone paired with a desktop sees and streams a browser page running on its server', async ({
testRepoPath
}, testInfo) => {
test.setTimeout(180_000)
const { host, desktop, phone, dispose } = await launchPhoneMirrorTopology(
{ phoneTo: 'desktop' },
testInfo
)
try {
await host.client.call('repo.add', { path: testRepoPath, kind: 'git' })
let serverHostId = ''
await expect
.poll(
async () =>
(serverHostId = await desktop.page.evaluate(
(repo) =>
window.__store
?.getState()
.allWorktrees()
.find((worktree) => worktree.path === repo)?.hostId ?? '',
testRepoPath
)),
{ timeout: 30_000 }
)
.toMatch(/^runtime:/)
const socket = await phone.openSocket()
let worktreeId = ''
await expect
.poll(async () => {
const id = nextId('host-worktrees')
socket.send(id, 'mobileRelay.hosts.worktrees', { hostId: serverHostId })
const listed = HostWorktreesSchema.safeParse((await reply(socket, id)).result)
worktreeId = listed.success
? (listed.data.worktrees.find((row) => row.path === testRepoPath)?.worktreeId ?? '')
: ''
return worktreeId
})
.not.toBe('')
const worktree = `id:${worktreeId}`
const { browserPageId } = await call(
socket,
{
id: 'browser-create',
method: 'browser.tabCreate',
params: {
worktree,
url: 'data:text/html,<body style="background:%23c33"><h1>server page</h1></body>',
activate: true
},
executionHost: serverHostId
},
CreatedSchema
)
// The server's tab list, read through the desktop, holds the page the server runs.
await expect
.poll(async () => {
const { tabs } = await call(
socket,
{
id: nextId('tabs'),
method: 'session.tabs.list',
params: { worktree },
executionHost: serverHostId
},
TabsSchema
)
return tabs.some((tab) => tab.type === 'browser' && tab.browserPageId === browserPageId)
})
.toBe(true)
socket.send(
'screencast',
'browser.screencast',
{
worktree,
page: browserPageId,
format: 'jpeg',
quality: 72,
maxWidth: 800,
maxHeight: 600,
everyNthFrame: 1,
minFrameIntervalMs: 100
},
serverHostId
)
let subscriptionId = ''
await expect
.poll(() => {
for (const frame of socket.frames) {
const ready = ReadySchema.safeParse(frame.result)
if (frame.id === 'screencast' && ready.success) {
subscriptionId = ready.data.subscriptionId
}
}
const failed = socket.frames.find((frame) => frame.id === 'screencast' && !frame.ok)
expect(failed, `browser.screencast: ${JSON.stringify(failed?.error)}`).toBeUndefined()
return subscriptionId
})
.not.toBe('')
// The page paints on the phone: real JPEG frames the server encoded, passed through the desktop.
await expect.poll(() => socket.screencastFrames.length, { timeout: 30_000 }).toBeGreaterThan(0)
const [first] = socket.screencastFrames
expect(first.format).toBe('jpeg')
expect([...first.image.subarray(0, 3)]).toEqual(JPEG_MAGIC)
await call(
socket,
{
id: 'screencast-stop',
method: 'browser.screencast.unsubscribe',
params: { subscriptionId },
executionHost: serverHostId
},
z.looseObject({ unsubscribed: z.literal(true) })
)
} finally {
await dispose()
}
})
@@ -1,81 +0,0 @@
import '../../../src/main/runtime/orca-runtime-tests/runtime-test-module-registration.spec'
import { afterEach, expect, it, vi } from 'vitest'
import { applyPtyBinding } from '../../../src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update'
import { committingSpawn } from '../../../src/main/runtime/orca-runtime-tests/bind-first-pane.test-fixture'
import { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime'
import {
TEST_WORKTREE_ID as WT,
TEST_WORKTREE_PATH
} from '../../../src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec'
import type { RuntimeMobileSessionTabsResult } from '../../../src/shared/runtime-session-contracts'
import type { RuntimePtyController } from '../../../src/main/runtime/terminal/lifecycle/runtime-pty-controller-contract'
import { createRuntimeFixture } from './active-tab-publication.test-fixture'
afterEach(() => vi.useRealTimers())
it('publishes admitted terminal placement independently of the selected split group', async () => {
vi.useFakeTimers()
const { runtime, runtimeStore, getSession } = createRuntimeFixture(false)
const ids = ['serve-active']
runtimeStore.persistPtyBinding = vi.fn(async (input) => {
const args = typeof input === 'function' ? input() : input
if (!args) {
return false
}
applyPtyBinding(args, getSession(), args.worktreeId, `${args.tabId}:${args.leafId}`)
return true
})
const controller: RuntimePtyController = {
spawn: committingSpawn(runtime, async () => {
const id = `serve-created-${ids.length}`
ids.push(id)
return { id }
}),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null,
listProcesses: async () => ids.map((id) => ({ id, cwd: TEST_WORKTREE_PATH, title: 'sh' }))
}
runtime.setPtyController(controller)
runtime.syncWindowGraph(0, { tabs: [], leaves: [] })
const list = () => runtime.listMobileSessionTabs(`id:${WT}`)
const second = await runtime.createMobileSessionTerminal(`id:${WT}`, { activate: false })
const firstGroup = (await list()).tabGroups![0]!.id
await runtime.moveMobileSessionTab(`id:${WT}`, {
kind: 'split',
tabId: second.tab.parentTabId,
targetGroupId: firstGroup,
splitDirection: 'right'
})
const right = (await list()).tabGroups!.find((group) => group.id !== firstGroup)!.id
const phone = await runtime.createMobileSessionTerminal(`id:${WT}`, {
activate: false,
targetGroupId: right
})
const selected = await list()
expect(selected.activeGroupId).toBe(right)
await vi.runAllTimersAsync()
const seen: RuntimeMobileSessionTabsResult[] = []
runtime.onMobileSessionTabsChanged((snapshot) => seen.push(snapshot))
const created = await runtime.createTerminal(`id:${WT}`, { focus: false })
expect(created.tabId).toBeDefined()
const saved = getSession().tabGroups![WT]!
expect(saved.find((group) => group.id === firstGroup)?.tabOrder).toContain(created.tabId)
expect(saved.find((group) => group.id === right)?.tabOrder).not.toContain(created.tabId)
const result = await list()
await vi.runAllTimersAsync()
const expected = [
[firstGroup, ['serve-tab', created.tabId]],
[right, [second.tab.parentTabId, phone.tab.parentTabId]]
]
expect(result.tabGroups?.map((group) => [group.id, group.tabOrder])).toEqual(expected)
expect(seen.at(-1)?.tabGroups?.map((group) => [group.id, group.tabOrder])).toEqual(expected)
expect(result.activeGroupId).toBe(right)
expect(result.activeTabId).toBe(selected.activeTabId)
const reloaded = new OrcaRuntimeService(runtimeStore)
reloaded.setPtyController(controller)
const cold = await reloaded.listMobileSessionTabs(`id:${WT}`)
expect(cold.tabGroups?.map((group) => [group.id, group.tabOrder])).toEqual(expected)
})